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

Susan Sarandon
Release: 2024-10-26 00:50:03
Original
526 people have browsed it

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>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!