loading...
Cover image for CSS Nugget: Text Divider in Flexbox
CodyHouse

CSS Nugget: Text Divider in Flexbox

guerriero_se profile image Sebastiano Guerriero ・1 min read

In this tutorial, we'll create a fluid text divider with a single <div>, with the help of Flexbox and pseudo-elements.

Preview

HTML

The structure is super simple: a single <div> containing the label of the divider.

<div class="text-divider">Text divider</div>

CSS

We can use the ::before and ::after pseudo-elements to create two lines on both sides of the label. Because we set the display property of the .text-divider equal to flex, we can apply flex-grow: 1 to the pseudo elements to have them occupy all the available space.

.text-divider {
  display: flex;
  align-items: center; // align text and lines vertically
}

.text-divider::before,
.text-divider::after {
  content: '';
  height: 1px;
  background-color: silver;
  flex-grow: 1; // both lines will expand to occupy the available space
}

A final touch would be using a CSS custom property to set the gap between the label and the lines:

.text-divider {
  display: flex;
  align-items: center;
  --text-divider-gap: 1rem; // set a customizable gap between label and lines
}

.text-divider::before,
.text-divider::after {
  content: '';
  height: 1px;
  background-color: silver;
  flex-grow: 1;
}

.text-divider::before {
  margin-right: var(--text-divider-gap);
}

.text-divider::after {
  margin-left: var(--text-divider-gap);
}

Posted on by:

guerriero_se profile

Sebastiano Guerriero

@guerriero_se

UX/UI designer, creating stuff at CodyHouse.

CodyHouse

We eat pizza 🍕, drink coffee ☕️, and ship web design products 🤖.

Discussion

pic
Editor guide