显示内联广告块未水平增长,并且孩子的填充百分比为 [英] Display inline-block not growing horizontally with child having padding in per cent

查看:49
本文介绍了显示内联广告块未水平增长,并且孩子的填充百分比为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将一个img标签放入一个内联块元素中并对其进行填充时,父元素不会按预期增长.

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

推荐答案

使用百分比值将父级宽度视为参考.在这里,您有一种循环,因为宽度也是基于内容的.

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>

此处有更多详细信息: https://www.w3.org/TR/css-sizing-3/#percentage-sizing

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).

另一个示例,该图像使用其初始宽度的50%用于定义容器的大小:

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:

为什么填充百分比会破坏我的弹性商品?

CSS网格-不必要的断字

如果想继续使用百分比填充,则可以在Chrome上运行的 hack 是考虑一种不可见的动画,该动画将再次触发宽度计算,并且您将再也不会出现溢出:

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>

这篇关于显示内联广告块未水平增长,并且孩子的填充百分比为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆