CSS horizontal line on one side of the text

I want to create a horizontal line on the left side of my text. I have something like this, but it creates a 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/

+4
source share
4 answers

With your current HTML structure, you can use Flexboxand :after, :beforepseudo-elements for 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>
Run codeHide result
+3
source

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

In the example below, I "hid" the right /: after the 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>
Run codeHide result
+1

- this? .

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>
Hide result
+1

Use div:

CSS

.line { display: inline-block; width: 100px; height: 1px; background-color: #000; }
h2 { display: inline-block; }

HTML

For the left horizontal:

<div class="line"></div>
<h2>Text Goes here</h2>

For the right horizontal:

<h2>Text Goes here</h2>
<div class="line"></div>
0
source

All Articles