我有一个布局,其中容器的固定高度和宽度为 640px x 480px
。在这个容器中有 3 个 div,top
、mid
和 bot
。我希望这 3 个 div 适合容器,前提是它们不会溢出容器。 top
和 bot
div 没有固定高度,而 mid
应该适合 top 和 bot 之间的空间。
我已经尝试过的是这样的:
HTML
<div class="main">
<div class="top">
</div>
<div class="mid">
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Chestnut-breasted_Malkoha2.jpg/593px-Chestnut-breasted_Malkoha2.jpg" />
</div>
<div class="bot">
</div>
</div>
CSS
.main {
padding: 10px;
width: 640px;
height: 480px;
display: inline-block;
background: #000;
position: relative;
}
.top {
width: 100%;
height: 50px;
display: block;
background: #eee;
}
.mid {
width: 100%;
height: 100%;
display: block;
background: #333;
}
img {
max-width: 100%;
max-height: 100%;
margin: 0 auto;
display: block;
}
.bot {
width: 100%;
height: 50px;
display: block;
background: #ccc;
}
现在我的问题是将机器人推到容器外。我怎样才能使它们适合容器而不使用溢出:隐藏?提前致谢。
注意:
the image should fit inside the mid
container.
更新 top
和 bot
div 可以包含段落,因此它的高度不固定。
最佳答案
检查这个示例:
.main {
padding: 50px 0px;
width: 640px;
height: 480px;
display: block;
background: #000;
position: relative;
box-sizing: border-box;
-moz-box-sizing: border-box;
}
.top {
width: 100%;
height: 50px;
display: block;
background: #eee;
position: absolute;
top : 0;
left : 0;
}
.mid {
width: 100%;
height: 100%;
display: block;
background: #333;
}
img {
max-width: 100%;
max-height: 100%;
margin: 0 auto;
display: block;
}
.bot {
width: 100%;
height: 50px;
display: block;
background: #ccc;
position: absolute;
bottom : 0;
left : 0;
}
更新:
也可以使用表格,以获得更灵活的框。
http://jsfiddle.net/jslayer/U3EaZ/
HTML:
<div class="box">
<div class="h"> Hello<br/>Cruel<br/>World </div>
<div class="m">
<img src="http://goo.gl/a1smCR" alt="" />
</div>
<div class="b"> Omg </div>
</div>
CSS:
.box {
display: table;
width: 640px;
height: 480px;
background: red;
}
.h, .m, .b {
display: table-row;
}
.h {
background: yellow;
height: 0;
}
.m {
background: green;
}
.m img {
max-width: 100%;
height: 100%;
max-height: 100%;
margin: 0 auto;
display: block;
}
.b {
background: blue;
height: 0;
}
关于css - 将 div 垂直放置在具有固定高度和宽度的父 div 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22804057/