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

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

Linda Hamilton
Linda HamiltonOriginal
2024-12-09 00:21:10570browse

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

Add Centered Text to the Middle of a Horizontal Rule

Originally, the question posed ways to separate text using horizontal rules in xhtml 1.0 strict. However, the provided methods exhibited alignment issues, prompting a request for an elegant solution.

The answer introduces Flexbox as the key to solving this problem. Here's a breakdown of the provided code:

  • .separator { ... } defines a style for the main element.
  • display: flex; sets it to be a flex container.
  • align-items: center; ensures that items within the flexbox are vertically centered.
  • text-align: center; centers the text content.

To create the horizontal rule, the following style is applied:

  • .separator::before, .separator::after { ... } targets pseudo-elements before and after the content.
  • content: ''; removes any content from the pseudo-elements.
  • flex: 1; ensures that they occupy the available space equally.
  • border-bottom: 1px solid #000; creates the desired line effect.

To add spacing around the text, the following styles are applied:

  • .separator:not(:empty)::before { ... } and .separator:not(:empty)::after { ... } target the pseudo-elements only when there is text content.
  • margin-right and margin-left add margins to the left and right of the text, providing separation from the horizontal rules.

The HTML code demonstrates how to use this style:

  • wraps the text in the .separator element.

This solution utilizes Flexbox's advanced layout capabilities to achieve centered text and horizontal rules with ease and elegance.

The above is the detailed content of How Can I Center Text Within a Horizontal Rule 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