Home  >  Article  >  Web Front-end  >  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
Barbara StreisandOriginal
2024-10-27 05:32:29637browse

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>

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>

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>

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!

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