Как сделать вертикальную линию в html
Перейти к содержимому

Как сделать вертикальную линию в html

  • автор:

How to draw vertical and diagonal lines with HTML and CSS

As someone just starting out with HTML and CSS there are a few things (to say the least) that can immediately perplex. For me it was vertical lines. Wanna make a horizontal line? Cool. Throw in an <hr> tag and you're good to go. Wanna make a vertical line? Logic would dictate you throw in a <vr> tag and you're good to go. Wait, no?

Now we have to get a little creative. I'll share three methods for making vertical lines (and diagonal too just for fun ☺).

Rotating a Horizontal line

The first method is to take a horizontal line and use the transform property to rotate it. For a vertical line you would rotate it 90 degrees.

Slightly confusingly, in order to change the height of the line, you'll need to change the width property because after all, this is just a horizontal line turned on it’s side.

The fun thing though, is that you can turn it into a diagonal just by changing the degree of rotation!

To move the line around the page you can add the parameters translateX and translateY to the transform property. This will move the line along the X and Y axis respectively.

A <div> with a width of 1px

The next method is to create a <div> that has the width of 1px (or more depending on how thick you’d like the line). For this method you'll have to specify a class on the <div> so as not to confuse the styling with other <div>s on your page

This may seem a little less intuitive that just rotating a horizontal line, but the benefit is that in order to change the height, you change the height property and don’t have to bend your mind every time you want to modify it a little. Another benefit is that you can make the line as thick as you would like by adjusting the width property.

But don't forget to add a background colour or border-left or border-right colour or you'll be wondering why you can't see the line ;).

The transform property works the same way as in the previous method to make diagonal lines as well.

Border-Left/Right on an existing <div>

One way to make your life a little easier is to use what’s already there. For instance, if you like to put vertical lines between text and you already have some paragraphs floating next to each other, you could just put a border-right property and voila! a vertical line separating the text. This saves you making extra <div>s for each line.

The above code will result in the following vertical lines.

You might be thinking “but I only wanted lines between the text, this method isn't going to work for me”. But wait, there’s more!

By simply adding a <div> around the paragraphs and adding a last:child pseudo selector with no border you’re problems are solved.

Как сделать вертикальную линию HTML?

Как сделать вертикальную линию HTML?

В продолжение темы оформления контента на станицах сайта сегодня я хочу вам показать, как можно добавить вертикальную линию HTML, и тем самым выделить фрагмент текста, сделав его более заметным для посетителей.

Для того, что бы сделать вертикальную линию HTML есть несколько способов, но в зависимости от браузера у вас могут возникнуть проблемы с ее отображением на странице. Поэтому я покажу вам два наиболее простых способа добавления вертикальной линии HTML, которые будут у вас на 100% работать.

Навигация по статье:

Вертикальная линия HTML

В первом случае нам нужно обернуть предназначенный для выделения фрагмент текста или элемент на странице в тег <div>, или же использовать уже существующий блок, и для этого блока задать границу с нужной стороны.

Можно дописать стили в самом теге:

Вертикальная линия HTML

С помощью свойства border-left мы задаем границу блока с левой стороны, и задаем следующие параметры границы:

  • 3px – толщина линии
  • solid – сплошная линия.Так же можно сделать: пунктирную(dotted), прерывистую (dashed), double (двойную), вогнутую (groove), и выпуклую (ridge).
  • red – это цвет границы. Его вы можете задать названием цвета, в шестнадцатеричном формате, с помощью таблицы цветов RGB или RGBA.

Для задания границы вы можете использовать следующие свойства:

  • border-left – граница слева
  • border-right— граница справа
  • border-top – сверху
  • border-bottom – снизу
  • border – граница по всему контуру блока

Так же нам нужно указать отступ текста от границы с помощью свойства padding-left, иначе он будет к ней прилипать. В моем случае отступ равен 10 пикселям.

Если вам удобнее работать с CSS стилями в отдельном файле, то для блока нужно присвоить класс и для этого класса прописать данные свойства в CSS -файле. Вот как это будет выглядеть:

HTML:

CSS:

Вертикальная линия HTML для текста в блоке

Вертикальная линия HTML с помощью псевдоэлемента

Если вам удобнее работать с CSS -стилями, то вы можете воспользоваться еще одним способом добавления вертикальных линий. Данный вариант немного сложнее и заключается в использовании псевдоэлементов :before и :after. Но у псевдоэлементов есть один очень ощутимый плюс, они позволяют без добавления HTML-кода, разместить на станице, соответственно, перед блоком или после него дополнительный элемент.

Тема псевдоэлементов достаточно обширна, поэтому подробно вдаваться их описание я сейчас не буду. В ближайшее время постараюсь подготовить статью с более подробной информацией по наиболее полезным псевдоэлементам, их возможностям и применению.

Итак, если нам нужно разместить вертикальную или горизонтальную линию сверху или слевой стороны элемента, то нам нужно использовать псевдоэлемент :before. Если же линия должна быть справа или снизу, то мы должны использовать псевдоэлемент :after.

How to make a vertical line in HTML

Put a <div> around the markup where you want the line to appear to next, and use CSS to style it:

jacefarm's user avatar

You can use the horizontal rule tag to create vertical lines.

By using minimal width and large size, horizontal rule becomes a vertical one.

You can use an empty <div> that is styled exactly like you want the line to appear:

HTML:

With exact height (overriding style in-line):

Style the border if you want 3D look:

You can of course also experiment with advanced combinations:

You can also make a vertical line using HTML horizontal line <hr />

miller's user avatar

Ishan Jain's user avatar

There is no vertical equivalent to the <hr> element. However, one approach you may want to try is to use a simple border to the left or right of whatever you are separating:

miller's user avatar

HTML5 custom elements (or pure CSS)

enter image description here

1. javascript

Register your element.

*The — is mandatory in all custom elements.

2. css

*You might need to fiddle a bit with display:inline-block|inline because inline won’t expand to containing element’s height. Use the margin to center the line within a container.

3. instantiate

*Unfortunately you can’t create custom self-closing tags.

usage

enter image description here

Don’t want to mess with javascript?

Simply apply this CSS class to your designated element.

One other option is to use a 1-pixel image, and set the height — this option would allow you to float it to where you need to be.

Not the most elegant solution though.

You can draw a vertical line by simply using height / width with any html element.

miller's user avatar

There is a <hr> tag for horizontal line. It can be used with CSS to make horizontal line also:

The width property determines the thickness of the line. The height property determines the length of the line. The background-color property determines the color of the line.

Muminur Rahman's user avatar

There isn’t any tag to create a vertical line in HTML.

Method: You load a line image. Then you set its style like «height: 100px ; width: 2px»

Method: You can use <td> tags <td style=»border-left: 1px solid red; padding: 5px;»> X </td>

onurbaysan's user avatar

To create a vertical line centered inside a div I think you can use this code. The ‘container’ may well be 100% width, I guess.

miller's user avatar

Edd's user avatar

Rotate a <hr> 90 degrees:

MeKoo Solutions's user avatar

You can use hr (horizontal line) tag and than rotate it 90 degree with css below

Hayk Aghabekyan's user avatar

One more approach is possible : Using SVG.

  • You can have line of any length and orientation.
  • You can specify the width, color easily
  • SVG are now supported on most modern browsers. But some old browsers (like IE 8 and older) don’t support it.

I used a combination of the «hr» code suggested, and here’s what my code looks like:

I simply changed the value of the «left» pixel value to position it. (I used the vertical line to line-up content on my webpage, and then I removed it.)

Vertical line right to the div

Vertical line left to the div

pvrforpranavvr's user avatar

Why not use &#124, which is the html special character for |

If your goal is to put vertical lines in a container to separate side-by-side child elements (column elements), you could consider styling the container like this:

This adds a left border to all child elements starting from the 2nd child. In other words, you get vertical borders between adjacent children.

  • > is a child selector. It matches any child of the element(s) specified on the left.
  • * is a universal selector. It matches an element of any type.
  • :not(:first-child) means it’s not the first child of its parent.

I think this is better than a simple .child-except-first rule, because it makes more sense to have the vertical lines come from the container’s rules, not the different child elements’ rules.

Whether this is better than using a makeshift vertical rule element (by styling a horizontal rule, etc.) will depend on your use case, but this is an alternative at least.

How to Create Vertical Line in HTML

You might have a couple of reasons to create a vertical line on your web page but HTML does not have any element for vertical lines. Although HTML only have the element for a horizontal line; but still there are multiple ways to create a vertical line in HTML as mentioned below:

  • Using Border CSS Property
  • Using width and height CSS Property
  • Using hr Transform Property

Here in this article, we have explained all possible ways to create Vertical line in HTML:

1) Using Border-Right, Height and Position CSS Property

OUTPUT

2) Vertical line using Border-Left, Height, and Position CSS Property

3) Vertical line using hr Transform Property

A vertical line can be created in HTML using transform property in <hr> tag. With the help of this property, you can rotate a horizontal line to a vertical line.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *