当一个单元格div包含一个绝对定位的div时,如何在表格div中顶部对齐两个单元格div?
在此示例中,不包含绝对定位的div的单元格div被按下。
HTML:
<div id="table">
<div>
<div>1 11 1</div>
</div>
<div>
<div>
<div id="rightIsOnTop">
<div id="textThatIsBelow">textThatIsBelow</div>
<div id="textThatIsOnTop">on top</div>
</div>
</div>
</div>
</div>
CSS:
body, html {
font-size:x-large;
margin:0px;
padding:0px;
}
#table {
display: table;
z-index: 5; /* So that other elements can be put above or below this. */
position: relative;
}
#table > div {
display: table-cell;
}
#table > div > div {
vertical-align:top;
min-width:150px;
margin:10px;
background:grey;
}
#rightIsOnTop {
position:relative;
min-width:80px;
overflow:hidden;
}
#textThatIsBelow {
position: absolute;
white-space:nowrap;
display:inline-block;
}
#textThatIsOnTop {
float: right;
position:relative;
display:inline-block;
background:red;
}
这是它们的呈现方式:
这就是我希望它们呈现的方式:
感谢您的帮助
答案 0 :(得分:2)
您忘了将vertical-align: top;
添加到您的单元格div中,但不会添加到您的内容中。
应该是
#table > div {
display: table-cell;
vertical-align:top;}
答案 1 :(得分:1)
您可以使用css3的Flexbox模型来实现此目的:
.flexBox {
display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
display: -ms-flexbox; /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Chrome */
display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
您可以在子元素上使用flex属性来调整div的大小。
答案 2 :(得分:1)
此规则#textThatIsOnTop {float: right;}
会使框未对齐。
但是#textThatIsOnTop
position:absolute
对我来说听起来更合理,不需要浮动元素。它还将解决对齐问题。
#textThatIsBelow {
white-space:nowrap;
display:inline-block;
}
#textThatIsOnTop {
position: absolute;
right: 0;
top: 0;
display:inline-block;
background:red;
}
完整更新的代码/演示如下。
body, html {
font-size:x-large;
margin:0px;
padding:0px;
}
#table {
display: table;
z-index: 5; /* So that other elements can be put above or below this. */
position: relative;
}
#table > div {
display: table-cell;
}
#table > div > div {
vertical-align:top;
min-width:150px;
margin:10px;
background:grey;
}
#rightIsOnTop {
position:relative;
min-width:80px;
overflow:hidden;
}
#textThatIsBelow {
white-space:nowrap;
display:inline-block;
}
#textThatIsOnTop {
position: absolute;
right: 0;
top: 0;
display:inline-block;
background:red;
}
<div id="table">
<div>
<div>1 11 1</div>
</div>
<div>
<div>
<div id="rightIsOnTop">
<div id="textThatIsBelow">textThatIsBelow</div>
<div id="textThatIsOnTop">on top</div>
</div>
</div>
</div>
</div>