Search code examples
htmlcsscalc

Calc 100% is applied to div, instead of h2


I'm trying to create the yellow shadow under h2, like this: enter image description here

However, what I get is this:

enter image description here

I see that the source code uses calc 100% to get the width of :after element.

ul li a h3:after {
width: calc(100% + 30px);
display: block;
content: '';
background: #fbf36d;
margin-top: -0.7rem;
margin-left: -10px;
height: 0.8rem;
position: absolute;
z-index: -1;
transition: all 0.3s ease-out;

}

Below are my code snippet.

.thing h2 {
  position: relative;
}

.thing h2:after {
  content: "";
  width: 100%;
  background: #fbf36d;
  margin-top:-0.7rem;
  margin-left: 5px;
  height: 0.8rem;
  position: absolute;
  z-index: -1;
  transition: all 0.3s ease-out;
  display: block;
}
  <div class="thing">
    <h2>Here is the title</h2>
    <p>I just don't get it, why the 100% width is applied to the div, instead of h2. Amazing.</p>
  </div>

Supposedly I missed out on something. Any ideas?


Solution

  • You need to have the h2 as inline blocks. the h2 is normally acting the same as a div - which meens that it is 100% wide.

    If you make it inline-block, it will only take the width, that it needs.

    .thing h2 {
      position: relative;
      display:inline-block;
    }
    
    .thing h2:after {
      content: "";
      width: 100%;
      background: #fbf36d;
      margin-top:-0.7rem;
      margin-left: 5px;
      height: 0.8rem;
      position: absolute;
      z-index: -1;
      transition: all 0.3s ease-out;
      display: block;
    }
    <div class="thing">
        <h2>Here is the title</h2>
        <p>I just don't get it, why the 100% width is applied to the div, instead of h2. Amazing.</p>
      </div>