Home  >  Article  >  Web Front-end  >  How can I center headings with horizontal lines on either side using CSS?

How can I center headings with horizontal lines on either side using CSS?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 00:50:03593browse

How can I center headings with horizontal lines on either side using CSS?

CSS: Centered Headings with Horizontal Lines on Either Side

This challenge involves creating page titles (headings) that are centered with horizontal lines vertically centered on both sides, all while maintaining transparency for a background image.

To address this, consider the following solution:

<code class="css">h1 {
    position: relative;
    font-size: 30px;
    z-index: 1;
    overflow: hidden;
    text-align: center;
}
h1:before, h1:after {
    position: absolute;
    top: 51%;
    overflow: hidden;
    width: 50%;
    height: 1px;
    content: '\a0';
    background-color: red;
}
h1:before {
    margin-left: -50%;
    text-align: right;
}
.color {
    background-color: #ccc;
}</code>

In this code:

  • The h1 element is positioned relatively and horizontally centered.
  • Two pseudo-elements (:before and :after) are used to create the horizontal lines on both sides.
  • The lines are positioned absolutely, set to 51% from the top, and half the width of the heading.
  • To create the transparent area around the text, the overflow property of the h1 element is set to hidden.
  • To ensure the lines are hidden when overlapping the text, they are given a non-breaking space (a0) as their content.
  • The red background color makes the lines easily visible for demonstration purposes. Adjust it to match your desired styling.

This solution effectively centers the headings and creates the desired horizontal lines without introducing any additional HTML elements.

The above is the detailed content of How can I center headings with horizontal lines on either side using CSS?. 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