DEV Community

Cover image for CSS Nugget: Text Divider in Flexbox
Sebastiano Guerriero for CodyHouse

Posted on

CSS Nugget: Text Divider in Flexbox

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>
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
rainocode profile image
rainocode

Text dividers are a visually appealing way to break up content and add structure to your website. With the power of Flexbox in CSS, you can create elegant text dividers that seamlessly integrate into your design. In this CSS nugget tutorial, we'll explore how to leverage Flexbox to implement text dividers effortlessly, allowing you to achieve clean and modern layouts.visit site rainocode.com/blog/text-dividers-f...

Collapse
 
devzom profile image
Jacob

Great work, thanks. :)

Collapse
 
usmanzahidcode profile image
Usman Zahid • Edited

Here's for vertical one:

  .flex-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
  }
  .line {
    min-height: 70px;
    padding: 0 1px;
    background-color: black;
  }
Enter fullscreen mode Exit fullscreen mode
<div class="flex-container">
  <div class="line"></div>
  <p>OR</p>
  <div class="line"></div>
</div>
Enter fullscreen mode Exit fullscreen mode

Image description