Search code examples
htmlcssvertical-alignment

CSS: Vertically centering line


I am trying to vertically center a horizontal line on the website. Example: the yellow line in the image below:

enter image description here

I've tried the following code so far.

<div style="position:relative;">
<div style="position:absolute;left:50%;margin-  left:-50%;top:50%;margin-top:-1px;width:100%;height:2px;">
<div style="height:2px;border:none;color:#ffff00;background-color:#ffff00;"></div></div></div>

DEMO: https://jsfiddle.net/1kxw9g9o/

As well as this, but it still doesn't work.

<div style="display:flex;justify-content:center;align-items:center;">
<div style="width:100%;height:2px;">
<div style="height:2px;border:none;color:#ffff00;background-color:#ffff00;"></div></div></div>

DEMO: https://jsfiddle.net/ttkwxdnh/

Any ideas how to solve this? Thanks in advance.

EDIT: Thanks for all the answers. They work great, however I cannot get it to work the same way when I'm adding it to my website. After I paste the code the headline, and the text below it disappears, only showing the line. What am I missing? DEMO: http://jsfiddle.net/8a3vwkcp


Solution

  • Please use height:100% of your body, Html and parent div then it will be work

    html,
    body{height:100%}
    <div style="position:relative;height:100%">
    <div style="position:absolute;left:50%;margin-left:-50%;top:50%;margin-top:-1px;width:100%;height:2px;">
    <div style="height:2px;border:none;color:#ffff00;background-color:#ffff00;"></div></div></div>