0

How can I get my span element to fill up the width of its parent div element, while having some padding?

The code below causes its width to surpass that of its parent.

Code

    <div style="width: 30rem" id="parent">
      <span
        style="
          background-color: green;
          display: block;
          padding: 1rem;
          width: 100%;
        ">
       Span
     </span>
    </div>

enter image description here

  • 2
    i think it's because of padding. check [box-sizing](https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing) – Sfili_81 Jul 21 '22 at 07:50

1 Answers1

0

It's because of padding. your width is 100% plus padding. To prevent it use box-sizing property.

#parent {
  border: 3px solid;
}

span {
  background-color: green;
  display: block;
  padding: 1rem;
  width: 100%;
  box-sizing: border-box;
}
<div style="width: 30rem" id="parent">
  <span>
       Span
     </span>
</div>
Sfili_81
  • 2,377
  • 8
  • 27
  • 36