Home >Web Front-end >CSS Tutorial >How Can I Center Text Within a Horizontal Rule in HTML Using Flexbox?

How Can I Center Text Within a Horizontal Rule in HTML Using Flexbox?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 21:31:14936browse

How Can I Center Text Within a Horizontal Rule in HTML Using Flexbox?

Adding Centered Text to Horizontal Rules

The task of adding centered text within horizontal rules can be challenging in HTML. Various approaches have been suggested, but they often result in misalignment or clumsy solutions. Here's an elegant solution using Flexbox:

.separator {
  display: flex;
  align-items: center;
  text-align: center;
}

.separator::before,
.separator::after {
  content: '';
  flex: 1;
  border-bottom: 1px solid #000;
}

.separator:not(:empty)::before {
  margin-right: .25em;
}

.separator:not(:empty)::after {
  margin-left: .25em;
}
<div class="separator">Next section</div>

This code creates a flexible container with centered text. The ::before and ::after pseudo-elements form the horizontal borders, while the :empty selector prevents unnecessary margin on an empty container. This solution provides clean alignment and easy customization of the separator style.

The above is the detailed content of How Can I Center Text Within a Horizontal Rule in HTML Using Flexbox?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn