Home > Enterprise >  Style a block with separate backgrounds on the block itself and the text within it
Style a block with separate backgrounds on the block itself and the text within it

Time:10-03

The effect I am after is to have different backgrounds on a block and the text within the block, like this:

body {
  background-color: indigo;
}
p {
  background-color: orange;
  text-align:center;
  font-size: 20px;
}
span {
  display: inline-block;
  padding: 0 0.5em;
  background-color: moccasin;
}
<p><span>Highlight this text</span></p>

Is there a way of doing this without the <span> element? So with just CSS and the following HTML markup?

<p>Highlight this text</p>

I was looking at the available list of pseudo-classes and pseudo-elements, but can't see anything which might work.

CodePudding user response:

Yes, and without pseudo element

body {
  background-color: indigo;
}

p {
  font-size: 20px;
  padding: 0 0.5em;
  display:table; /* fit text content*/
  margin:auto; /* center */
  background-color: moccasin; /* main background */
  box-shadow:0 0 0 200vmax orange; /* a huge shadow to simulate the second background */
  clip-path:inset(0 -100vmax); /* clip the shadow to show only left/right part of it */
}
<p>Highlight this text</p>

  • Related