Home > Web Front-end > CSS Tutorial > How to Create Elegant Centered Headings with Horizontal Bars Without Text Overlap?

How to Create Elegant Centered Headings with Horizontal Bars Without Text Overlap?

Barbara Streisand
Release: 2024-10-27 05:32:29
Original
757 people have browsed it

How to Create Elegant Centered Headings with Horizontal Bars Without Text Overlap?

Elegant Headings with Horizontal Bars

When creating centered headings with horizontal bars on either side, it can be tricky to avoid the bars crossing over the text. Here's a solution to achieve this effect using pure CSS:

Solution Overview

This method utilizes pseudo-elements to create the horizontal bars and places them at a specific position relative to the text. Additionally, a negative margin on one of the bars together with an overflow is applied to hide the bars where the text exists.

Implementation

To implement this solution, follow these steps:

  1. Define the following CSS rule for the heading:
<code class="css">h1 {
    position: relative;  
    font-size: 30px;  
    z-index: 1;
    overflow: hidden;
    text-align: center;
}</code>
Copy after login

This rule positions the heading, specifies the font size, and enables the overflow hiding.

  1. Create pseudo-elements for the bars:
<code class="css">h1:before, h1:after {
    position: absolute;
    top: 51%;
    overflow: hidden;
    width: 50%;
    height: 1px;
    content: '\a0';
    background-color: red;
}</code>
Copy after login

These pseudo-elements are placed at the center of the heading with a certain width and height, and they will function as the horizontal bars.

  1. Offset and align the left bar:
<code class="css">h1:before {
    margin-left: -50%;
    text-align: right;
}</code>
Copy after login

This rule applies a negative margin to the left bar to align it and ensure that it is hidden where the text appears.

By implementing these CSS rules, you can effortlessly create centered headings with horizontal bars that disappear when they cross over the text, without including any additional HTML elements.

The above is the detailed content of How to Create Elegant Centered Headings with Horizontal Bars Without Text Overlap?. 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