Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short Lines Either Side Text

Tags:

html

css

Using CSS and HTML there are a load of answers for adding a line either side of some text but these lines always fill the full width of the container. I only want these lines to be 150px in length either side of the text like this:

example of what the lines should look like

The text will be dynamic so may change in length and needs to be centred.

Here is some jsfiddle code I have been working on:

https://jsfiddle.net/vh0j4q1e/

<div id="container">

TEXT HEADING

#container {
width:800px;
text-align:center;
background-color:#ccc;
}
h1 {
position: relative;
font-size: 30px;
z-index: 1;
overflow: hidden;
text-align: center;
}
h1:before, h1:after {
position: absolute;
top: 51%;
overflow: hidden;
width: 50%;
height: 3px;
content: '';
background-color: red;
}
h1:before {
margin-left: -50%;
text-align: right;
}

Can anyone help improve this code so the lines appear as per the image above?

like image 948
Future Webs Avatar asked Dec 06 '22 18:12

Future Webs


2 Answers

You could use Flexbox here

h2 {
  display: flex;
  align-items: center;
  justify-content: center;
  text-transform: uppercase;
}

h2:after, h2:before {
  content: '';
  width: 150px;
  height: 2px;
  background: red;
  margin: 0 10px;
}
<h2>Lorem ipsum</h2>
like image 102
Nenad Vracar Avatar answered Dec 24 '22 02:12

Nenad Vracar


And if you don't want to use Flexbox, you could do it by making h1 an inline-block then offsetting the :before -150px to the left and :after to 100% left

#container {
  width:800px;
  text-align:center;
  background-color:#ccc;
  margin:0 auto;
}

h1 {
    position: relative;
    font-size: 30px;
    display: inline-block;
    padding:0 15px;
}

h1:before, h1:after {
    position: absolute;
    top: 50%;
    width: 150px;
    height: 3px;
    content: '';
    background-color: red;
    left:-150px;
}

h1:after {
  left: 100%;
}
<div id="container">
  <h1>TEXT HEADING</h1>
</div>

https://jsfiddle.net/azizn/vh0j4q1e/1/

like image 22
Aziz Avatar answered Dec 24 '22 00:12

Aziz