Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS horizontal line on one side of text

Tags:

html

css

I want to create horizontal line on left side of my text. I have somethink like this, but it's creating line on both sides but I want only on one side - left or right. How can I do this?

h2 {
  width: 100%;
  text-align: center;
  border-bottom: 1px solid #000;
  line-height: 0.1em;
  margin: 10px 0 20px;
}

h2 span {
  background: #fff;
  padding: 0 10px;
}

Demo: http://jsfiddle.net/7jGHS/

like image 888
Damian Avatar asked Jul 05 '16 11:07

Damian


3 Answers

With your current HTML structure you can use Flexbox and :after, :before pseudo elements to do this.

h2 {
  display: flex;
  align-items: center;
  justify-content: center;
}
h2 span {
  background: #fff;
  margin: 0 15px;
}
h2:before,
h2:after {
  background: black;
  height: 2px;
  flex: 1;
  content: '';
}
h2.left:after {
  background: none;
}
h2.right:before {
  background: none;
}
<h2 class="left"><span>THIS IS A TEST</span></h2>
<h2 class="right"><span>LOREM</span></h2>
<p>this is some content</p>
like image 141
Nenad Vracar Avatar answered Nov 03 '22 12:11

Nenad Vracar


I always try and use the :before and :after classes of CSS when trying to achieve this effect.

In the example below I have "hidden" the right/ :after line

h1 {
    overflow: hidden;
    text-align: center;
}
h1:before,
h1:after {
    background-color: #000;
    content: "";
    display: inline-block;
    height: 1px;
    position: relative;
    vertical-align: middle;
    width: 50%;
}
h1:before {
    right: 0.5em;
    margin-left: -50%;
}
h1:after {
    left: 0.5em;
    margin-right: -50%;
    display: none;
}
<h1>Heading</h1>
<h1>This is a longer heading</h1>
like image 40
Andrew Birks Avatar answered Nov 03 '22 14:11

Andrew Birks


Something like this? You can use pseudo elements and absolute positioning to do that.

h2 {
  position: relative;
  width: 100%;
  text-align: center;
  line-height: 0.1em;
  margin: 10px 0 20px;
}
h2:after {
  z-index: -1;
  position: absolute;
  /* Change "right: 0" to "left: 0" for left side line */
  right: 0;
  content: '';
  width: 50%;
  border-bottom: 1px solid #000;
}
h2 span {
  background: #fff;
  padding: 0 10px;
}
<h2><span>THIS IS A TEST</span></h2>
<p>this is some content</p>
like image 1
Pugazh Avatar answered Nov 03 '22 12:11

Pugazh