Display inline-block not growing horizontally with child having padding in per cent

牧云@^-^@ 提交于 2021-01-28 10:47:14

问题


When I put an img tag inside a inline-block element and give padding to it the parent isn't growing as it should.

article {
  background: fuchsia;
  display: inline-block;
}

img {
  padding: 5%;
}
<article>
  <img src="https://fakeimg.pl/412x412"/>
</article>

CodePen: https://codepen.io/Yarmolaev/pen/xxxbeJr


回答1:


It's the use of percentage value that consider the parent width as reference. Here you have a kind of cycle since the width is also based on the content.

In this case the browser is ignoring the padding to find the width of the container based on its content then the padding is calulated based on that width and added to the image to create the overflow. The browser will not go back to change the container width because it will be an infinte loop.

The only way to fix this is to consider fixed values:

article {
  background: fuchsia;
  display: inline-block;
}

img {
  padding: 10px;
}
<article>
  <img src="https://fakeimg.pl/412x412"/>
</article>

More details here: https://www.w3.org/TR/css-sizing-3/#percentage-sizing


This will happen in most of the cases where you use percentage value and where the container size is based on its content (shrink-to-fit behavior).

Another example where the image is taking 50% of its initial width used to define the container size:

article {
  background: fuchsia;
  float:left;
}

img {
  width:50%;
}
<article>
  <img src="https://fakeimg.pl/412x412"/>
</article>

Related questions with similar situations:

Why does percentage padding break my flex item?

CSS Grid - unnecessary word break


A hack that works on Chrome if want to keep the use of percentage padding is to consider a non visible animation that will trigger the calculation of width again and you will no more have the overflow:

article {
  background: fuchsia;
  display: inline-block;
}

img {
  padding: 5%;
  animation:change 0.3s infinite;
}

@keyframes change{
  to {
    padding:5.01%;
  }
}
<article>
  <img src="https://fakeimg.pl/412x412"/>
</article>


来源:https://stackoverflow.com/questions/58289173/display-inline-block-not-growing-horizontally-with-child-having-padding-in-per-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!