我目前正在尝试将图像放入 div 容器中,但它不起作用。我的页面上有一个复杂的 div 树,看起来像这样:
<div id="a">
<div id="b">
<div id="c">
<div id="d">
<img src="http://public.media.smithsonianmag.com/legacy_blog/npg_portraits_nicholson_jack_2002.jpg" />
</div>
</div>
</div>
</div>
以及以下 CSS:
#a {
height: 300px;
background-color: red;
position: relative;
text-align: center;
}
#b {
height: 100%;
width: 100%;
background-color: blue;
position: absolute;
top: 0;
left: 0;
text-align: center;
padding: 20px;
}
#c {
width: auto;
height: auto;
display: inline-block;
max-height: 100%;
background-color: black;
padding: 20px;
}
#d {
width: 400px;
background-color:yellow;
max-height: inherit;
}
img {
max-width: 100%;
opacity: 0.7;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
height: calc(100% - 80px);
margin: auto;
}
我希望图像适合蓝色容器。它还应该注意给定的 div 容器。目前黑色的直到最后才填充容器加上填充。
我希望有人能够提供帮助。
最佳答案
这是给你的一个新概念。 box-sizing: border-box
自动将填充合并到百分比宽度和高度中。图片不再需要 position: absolute
。
所有内部 div 的宽度和高度由 #a
容器的宽度及其填充控制。
新演示
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#a {
background-color: red;
position: relative;
text-align: center;
width: 400px;
padding: 20px;
}
#b {
background: blue;
padding: 20px;
}
#c {
background-color: black;
padding: 20px;
}
#d {
background-color: yellow;
padding: 20px;
}
img {
width: 100%;
display: block; /* remove inline gap */
}
<div id="a">
<div id="b">
<div id="c">
<div id="d">
<img src="http://public.media.smithsonianmag.com/legacy_blog/npg_portraits_nicholson_jack_2002.jpg" />
</div>
</div>
</div>
</div>
旧答案
删除
宽度:自动; height: auto;
andpadding: 20px
on#c
将
height: 100%
放在#c
上
发生这种情况的原因 - #c
的 height: 100%
受 #b
上的填充影响> 所以任何额外的填充都会使高度膨胀。
演示
#a {
height: 300px;
background-color: red;
position: relative;
text-align: center;
}
#b {
height: 100%;
width: 100%;
background-color: blue;
position: absolute;
top: 0;
left: 0;
text-align: center;
padding: 20px;
}
#c {
height: 100%;
display: inline-block;
background-color: black;
}
#d {
width: 400px;
background-color:yellow;
max-height: 100%;
}
img {
max-width: 100%;
opacity: 0.7;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
height: calc(100% - 80px);
margin: auto;
}
<div id="a">
<div id="b">
<div id="c">
<div id="d">
<img src="http://public.media.smithsonianmag.com/legacy_blog/npg_portraits_nicholson_jack_2002.jpg" />
</div>
</div>
</div>
</div>
关于html - div 内的图像缩放失败 - 背景不跟随,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26436859/