- Instant help with your CSS coding problems

Create horizontal rule with text using TailwindCSS

Question:
How to create horizontal rule with text using TailwindCSS?
Answer:
<div class="flex items-center">
    <div class="grow border-b border-teal-600"></div>
    <span class="shrink px-1 pb-1 text-teal-600">Content title</span>
    <div class="grow border-b border-teal-600"></div>
</div>
Description:

If you just want to change the colour, line type or thickness of the hr element, you can simply add the desired Tailwind classes.

For example, here is a code that creates a dashed blue horizontal rule:

<hr class="border-b border-dashed border-blue-600" />

And the result is:

A basic styled horizontal rule

Adding text to Horizontal Rule

To add the text to the hr element, you need to add slightly more classes and pay more attention to the appropriate values.

<hr
    class="border-t-[1px] border-dotted border-red-600 h-1 text-center overflow-visible 
    after:content-['Content_title'] after:relative after:top-[-14px] after:bg-white after:text-red-600 after:px-1"
/>

The code above will generate the following output:

HR element with text

What to look out for in this solution: 

  • The space character should not be used in the text, it should be replaced by an underscore _ character.
  • The background colour should also be set to match the background colour of the page

 

A slightly more code-intensive but cleaner solution might be to imitate the hr element like this:

<div class="flex items-center">
    <div class="grow border-b border-teal-600"></div>
    <span class="shrink px-1 pb-1 text-teal-600">Content title</span>
    <div class="grow border-b border-teal-600"></div>
</div>

And the result is:

HR divider with text

 

Share "How to create horizontal rule with text using TailwindCSS?"
Interesting things
OpanAi's ChatGPT