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:
<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.
<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.
<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!