8

What's the best way to create the following in just CSS3 and using the fewest containers?

enter image description here

At the moment I'm using 2 nested divs and an hr which seems excessive.

Hopstream
  • 6,391
  • 11
  • 50
  • 81

4 Answers4

10

Pseudo-elements!

Using ::before and ::after you can manage this with just one container.

You'll need to adjust your values for your own environment, but the general idea is to position the pseudo-elements absolutely inside the container.

#or {
  position: relative;
  width: 300px;
  height: 50px;
  
  line-height: 50px;
  text-align: center;
}

#or::before,
#or::after {
  position: absolute;
  width: 130px;
  height: 1px;
  
  top: 24px;
  
  background-color: #aaa;
  
  content: '';
}

#or::before {
  left: 0;
}

#or::after {
  right: 0;
}
<div id="or">OR</div>

Using flexbox instead of absolute positioning is another option, with worse support.

Oka
  • 23,367
  • 6
  • 42
  • 53
8

.or {
  display:flex;
  justify-content:center;
  align-items: center;
  color:grey;
}

.or:after,
.or:before {
    content: "";
    display: block;
    background: grey;
    width: 30%;
    height:1px;
    margin: 0 10px;
}
<div class="or"> OR </div>
chillvivek
  • 290
  • 1
  • 7
1

HTML

<div class="separator"></div>

CSS

.separator {
    width: 100%;
    border-bottom: solid 1px;
    position: relative;
    margin: 30px 0px;
}

.separator::before {
    content: "OR";
    position: absolute;
    left: 47%;
    top: -8px;
    background-color: #fff;
    padding: 0px 10px;
}

Fiddle: https://jsfiddle.net/k9jmgdyq/1/

Vincent Panugaling
  • 896
  • 1
  • 12
  • 28
0

The html

<div class="separator"><label>OR</label></div>

And css

.separator{
    position: relative;
    text-align: center;
}

.separator label{
    background-color:#fff;
    padding: 0 0.4em;
    position: relative;
}

.separator:before{
    content: '';
    border-style: solid;
    border-width: 0 0 1px 0;
    position: absolute;
    left: 0;
    top: 50%;
    width: 100%;
    border-color:black;
}

Demo http://jsfiddle.net/0e6j7ruc/

Juank
  • 6,096
  • 1
  • 28
  • 28