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
Release: 2024-12-06 21:31:14
Original
1004 people have browsed it

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;
}
Copy after login
<div class="separator">Next section</div>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template