我在容器中有四个 div
元素:
<div id="container">
<div id="top"></div>
<div id="bottom-left"></div>
<div id="bottom-center"></div>
<div id="fill"></div>
</div>
我需要按如下方式定位它们:
top
元素的上边缘应该在容器的上边缘。
bottom-left
元素应该位于容器的左下角。
bottom-center
元素应该在容器底部居中。
fill
元素将具有固定宽度,并应垂直占据剩余空间。
问题在于 fill
元素将包含任意文本并且可以是任意高度。我需要将它放在 top
元素下,并将 bottom-center
放在它下面。 bottom-left
的底部边缘必须与 bottom-center
的底部对齐。
我试过绝对定位,但它不适用于任意文本长度。
如有任何帮助,我将不胜感激。
编辑:这里是 jsfiddle 代码:http://jsfiddle.net/gCg29/ 它创建了我想要实现但带有表格的布局。
如何摆脱表格并具有相同的功能?请注意,如果浏览器窗口的宽度不足,则元素不会重叠。还要注意,如果文本的长度增加,那么左下角和文本下方的元素会粘在文本的底部。
+-----------------------+
| top (fixed size) |
+-----------------------+
+-----------------------------------+
| |
| fill |
| (arbitrary height, |
+-----------------+ | fixed width) |
| | | |
| bottom-left | | |
| (fixed size) | | |
| | | |
| | | |
| | | |
| | | |
| | +-----------------------------------+
| | +--------------------------+
| | |bottom-center (fixed size)|
+-----------------+ +--------------------------+
最佳答案
给你:
#container {
position: relative;
overflow: hidden;
}
#fill {
margin: 0 auto 50px; /* 50px = height of bottom-center */
width: 300px;
}
#top, #bottom-center {
height: 50px;
width: 200px;
margin: 0 auto;
}
#bottom-center {
position: absolute;
bottom: 0;
left: 50%;
margin-left: -100px; /* - width / 2 */
}
#bottom-left {
position: absolute;
left: 0;
bottom: 0;
}
重要的部分是 overflow: hidden;
在容器上,这将使 #fill
上的边距扩大其大小,以便 #bottom-center
适合。
关于css - 如何使用 CSS 堆叠元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13206161/