Text in Border CSS HTML
To embed text in a border using CSS, take advantage of pseudo-elements such as ::before
or ::after
coupled with the content
property. Properly position the text over your element's border with this strategy:
Then apply it to a bordered element:
Make further adjustments for positioning (top) and appearance blending (background) to accommodate the overall design.
<fieldset> and <legend>: Semantics and Organization
The HTML essentials
For a consistent structure and accessible design, lean on the <fieldset>
and <legend>
. This pairing is perfect when you want to integrate text within styled borders while ensuring your HTML stays semantic:
Customizing the <fieldset>
with CSS gives you control over the border itself, while <legend>
manages the title.
Boosting readability: Padding, negative margins and more
By setting display: inline-block
to your text, you're promoting a natural width adjustment. Defining margin-top
in em
units for titles preserves their size relation with font sizes. All of this, plus a touch of CSS padding, crafts an inviting border illusion.
Ever walked and texted only to stumble upon a wall? To avoid that on the web page, add background images on div
elements or apply relative and absolute positioning across elements within the div.
<fieldset> Animation in jQuery
Making the border dance (not literally!)
Nothing screams engagement like added animations. Rev up your visual appeal with jQuery animations on the <fieldset>
:
This code spices things up by changing the border color to red when the fieldset is clicked. Yeah, take that static borders!
More Scenarios, More Power
Negative margins to the rescue
Apply negative margins to break the monotony of borders:
Flex your design with flex-direction
Achieve a neat and modern look with a vertical layout using the flexbox's flex-direction
property.
Enter the pseudo-elements, exit boredom
Play around with ::before and ::after pseudo-elements:
This adds an understated line beneath the text. Little details make the difference!
Keep text visible when parent element is hidden
Keep essential elements (like an h1 tag) visible by detaching and prepending them to the body:
Your h1 tag now pulls a Houdini as its parent div gets hidden!
Was this article helpful?