css - 将 div 垂直放置在具有固定高度和宽度的父 div 上

标签 css html

我有一个布局,其中容器的固定高度和宽度为 640px x 480px。在这个容器中有 3 个 div,topmidbot。我希望这 3 个 div 适合容器,前提是它们不会溢出容器。 topbot 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;
}

FIDDLE HERE

现在我的问题是将机器人推到容器外。我怎样才能使它们适合容器而不使用溢出:隐藏?提前致谢。

注意: the image should fit inside the mid container.

更新 topbot div 可以包含段落,因此它的高度不固定。

最佳答案

检查这个示例:

http://jsfiddle.net/J6QTg/8/

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

相关文章:

html - 使用位置 :fixed side-by-side each other 定位元素

html - 按钮中的垂直文本

javascript - 带有打开页面的 JQuery PopUp 的 Material Design HTML5 (.html)

html - 为什么这个 div 被完全推出它的父级?

html - 是否有可能为 html5 进度标签着色?

css - 溢出 : scroll is ignored

javascript - 是否可以仅在某些浏览器宽度时更改 div 的顺序(不仅仅是美学上的)?

javascript - 使用 JavaScript 在表中添加和删除行

iphone - 如何在我的网站上嵌入视频以便在 iPhone 上运行以及需要什么视频格式?

javascript - 社交媒体按钮不会出现在 BlogSpot 上