我想要一个CSS解决方案(原则上是HTML5 / CSS3),它将重现以下基于表格的布局的行为:
<table width="80%" align="center" border="1">
<tr valign="top">
<td>Some content that varies in size</td>
<td width="200">Maybe an image, maybe some short text</td>
</tr>
</table>
&#13;
我对CSS的最佳尝试让我得到左侧内容(&#34;大小不一的内容&#34;上面)以包裹右边的div。
这是我尝试的内容:
div.outsidecontainer {
position: relative;
width: 80%;
border: 1px solid silver;
margin-left: auto;
margin-right: auto;
}
div.absolute {
float: right;
width: 200px;
margin-bottom: 1px;
border: 1px solid silver;
}
div.filler {
border: 1px solid silver;
margin-bottom: 1px;
}
&#13;
<div class="outsidecontainer">
<div class="absolute">This is the fixed-size div on the right</div>
<div class="filler">Another div element with a lot of text .....</div>
</div>
&#13;
有什么建议吗?
答案 0 :(得分:1)
你可以通过几种方式来实现这一目标。
不要使用右侧的浮动来获取右侧的内容,只需将其放在右侧即可。在每个容器内容上放置float: left;
并在容器底部放置clearfix:both;
:
您的方法 - 已修复
* {
box-sizing: border-box;
}
.outsidecontainer {
width: 100%;
border: 1px solid black;
}
.cell {
float: left;
}
.absolute {
width: 200px;
}
.filler {
width: calc(100% - 200px);
height: 100%;
}
/*used to stop the container from collapsing*/
.clearfix {
clear: both;
}
<div class="outsidecontainer">
<div class="filler cell">Another div element with a lot of text .....</div>
<div class="absolute cell">This is the fixed-size div on the right</div>
<div class="clearfix"></div>
</div>
或者,您可以使用display: table
使用div复制表。
显示:表格方法
.t-body {
width: 80%;
display: table;
}
.t-row {
display: table-row;
}
.t-cell {
display: table-cell;
border: 1px solid black;
}
.fw {
width: 200px;
}
<div class="t-body">
<div class="t-row">
<div class="t-cell">Another div element with a lot of text ....</div>
<div class="t-cell fw">This is the fixed-size div on the right</div>
</div>
</div>
答案 1 :(得分:0)
一个常见的模式是将父(&#34; outsidecontainer&#34;在这种情况下)设置为position: relative
,然后将子元素(&#34;绝对&#34;)设置为position: absolute
和right: 0
。此模式将position: absolute
子元素设置为约束到父元素的边界(而不是默认约束到&#39; body&#39;元素的边界)
这是float: right
(也适用)的替代方案
然后设置margin-right
以补偿&#34;绝对&#34;的宽度。格
div.outsidecontainer {
position: relative;
width: 80%;
border: 1px solid red;
margin-left: auto;
margin-right: auto;
}
div.absolute {
position: absolute;
right: 0; /* position to the right of "outsidecontainer" div */
width: 200px;
margin-bottom: 1px;
border: 1px solid blue;
}
div.filler
{
border: 1px solid black;
margin-bottom: 1px;
margin-right: 200px; /* compensate for "absolute" div's width */
}
&#13;
<div class="outsidecontainer">
<div class="absolute">
<p>This is the fixed-size div on the right</p>
<p>This is the fixed-size div on the right</p>
<p>This is the fixed-size div on the right</p>
</div>
<div class="filler">
<p>Another div element with a lot of text ..... </p>
<p>Another div element with a lot of text ..... </p>
<p>Another div element with a lot of text ..... </p>
<p>Another div element with a lot of text ..... </p>
<p>Another div element with a lot of text ..... </p>
<p>Another div element with a lot of text ..... </p>
</div>
</div>
&#13;