Search code examples
htmlcss

How to set a background color surrounding an <hr> element but not adjacent text


I am trying to add color surrounding an <hr> element but not the surrounding lines, something like this:

A horizontal line HTML element between two words, the horizontal line has been highlighted yellow in a separate notes app

enter image description here

I tried a div with a background-color set like so:

test
<div style="background-color: yellow;">
  <hr>
</div>
test

But it does not work.

Trying this instead:

<div style="background-color: yellow;">
  <hr>
  test
</div>

I noticed that the <hr>’s background can only really be styled by the surrounding text.

Is there a good way around this?


Solution

  • The default <hr> element is a single inset border, without height, so it can't display background. You can use box-shadow instead:

    .divider {
      box-shadow: 0 0 0 0.5rem yellow;
    }
    test
    <hr class="divider">
    test