Do you know how to add a horizontal line on both sides of text?
Here’s is a nice heading style with horizontal lines in the middle on both sides.
Do you know how to make this without adding additional div
s or images and still make it work on all background colors and responsive too?
Let’s learn now.
This is the heading element. Now in CSS, let’s create two lines using the pseudo elements ::before
and ::after
.
Now we get this.
We have the lines and text one below the other. We need them next to each other right? If you inspect element, you can see that the ::before
element, the text and the ::after
element are all child elements of h2
. So can we use flexbox to align them all horizontally?
But the lines disappear. Because in flexbox, all elements occupy least space by default. We need to give the elements some size. And also, we want both the lines to occupy same width. This CSS rule will do both.
And now we have this.
If you know flexbox, you must know how to align all these flex items vertically.
And that’s it. We’ve achieved the result :)
Lastly, you might want to add some space between the text and the lines. For this, you can add some right and left margins on the pseudo elements.
Neat right? This is responsive and doesn’t use any background-color trick. So works everywhere. Hope you liked it :)
Here’s the link to the demo on Codepen.
📘 Complete Guide to CSS Flex and Grid
If you loved this write-up and how it was explained, you’ll absolutely love my eBook CSS Flex and Grid. Check it out!
📨 Newsletter suggestion
I love Tailwind CSS. If you love it too, I highly recommend subscribing to this one 👇
Tailwind Weekly: Weekly newsletter about all things Tailwind CSS. New issue every Saturday.
Thanks for this tip, Shruti! Going to recreate in Tailwind.
Am creating some awesome stuff in Tailwind recently.
I would appreciate your feedback on this component that I created - https://play.tailwindcss.com/MotbiAE6Ja
Thanks once again! - Mbaziira
Thank you, Shruti 🙌
Means, a lot!