Add centered text to the middle of a horizontal rule
Insert text within a horizontal line using a span
within a div
, tailor-made with CSS. Apply position: relative;
and padding
on the text to center it above a border-top
acting as the rule. Here's a fine-tuned snippet:
This solution delivers centered text within a full-width horizontal line, creating an easily-recognisable design component.
The Flexbox revolution
When it comes to responsive design, there is no beating Flexbox. By setting a div
as container and applying display: flex; justify-content: center; align-items: center;
, you end up with a flexible and responsive design:
With Flexbox, there's no need for position
or top
values — the text centers itself like a well-disciplined monk!
The touch of pseudo-elements
For a touch of flair, conjure up :before
and :after
pseudo-elements within the Flexbox container. By assigning their content
to an empty string and chiseling with border-bottom
, balanced horizontal lines emerge like applause on either side of the text.
Use this method to create symmetric designs with minimal markup.
Manuscripts of mastery
The div/hr protocol
A trusty yet flexible technique entails using a div
and hr
combo. By governing the width and alignment of the div
, you can wield your span
-wrapped text just where you want it to be. Here's a sneak peek:
Harnessing viewport widths
When sizing for responsiveness, vw
(viewport width) and percentages (%
) are your best buddies. They calibrate the length of your horizontal rules to the viewport size, ensuring your design dances across different screen sizes.
Absolute precision with positioning
At times, you may require specific control over the positioning of your text. Position: absolute;
in conjunction with left
, right
, top
, and bottom
brings you to the controls. Do remember to set the parent container to position: relative;
to establish the scene.
The art of floating text
Lastly, the art of floating brings the confluence of hr
-wrapped text, creating slivers of line segments to cradle your text. Do remember to clear the floats -- trust me, they don't clear themselves.
Was this article helpful?