Home >Web Front-end >CSS Tutorial >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!