CSS使内部div匹配外部div高度

时间:2011-09-06 16:15:29

标签: css

我基本上制作了一个表格(截图:http://mason.gmu.edu/~vnguyenl/form.jpg),其中有2列。标签列和输入列。标签面位于具有自己的bg颜色的div中,与输入字段侧相同。我试图这样做,以便如果一侧的文本多于另一列的文本将匹配它的高度。现在,如果一方比另一方大,那就有空隙。非常感谢任何帮助!感谢。

表单的html如下所示:

<div class="formRow">
<div class="labelColumn">Last Name: Last Name: Last Name: Last Name: Last Name: Last Name: Last Name: Last Name: Last Name: Last Name: Last Name: Last Name: <span class="required">*</span></div>
<div class="contentcolumn">
    <input class="textBox300" type="text" id="last_name"  tabindex="1"  />
</div>
</div>

css如下:

#pt-profile-form .labelColumn, .labelColumn2 {
font-weight:bold;
float:left;
width:300px; /* Width of left column */
margin-left:0px;
background:#f0f4f7;
text-align:left;
padding:5px;
padding-left:14px;
display:block;
white-space:normal;
position:relative;
clear:both;
}

#pt-profile-form .formRow { clear:both; height:100%;  }

#pt-profile-form .contentcolumn, .contentcolumn2 {
margin-left:320px; /* Set left margin to LeftColumnWidth */
background-color:#eae9d7;
padding:5px;
text-align:left;
vertical-align:middle;
position:relative;
}

#pt-profile-form .labelColumn, .contentcolumn {
/*height:30px;*/
min-height:30px;
height:100%;
}

#pt-profile-form .labelColumn2, .contentcolumn2 { /* column properties for <textarea>     */
/*height:100px;*/
height:100%;
}

1 个答案:

答案 0 :(得分:1)

简单解决方案

据我所知,实现这一目标的唯一方法是将背景颜色放在包裹元素上(在您的情况下为<div class="formRow">),然后确保使用包裹元素将包裹元素推到整个高度清算,正如@MarcB在评论中提到的那样(http://quirksmode.org/css/clearing.html)。

所以下面的CSS应该修复它:

.formRow {
    overflow: auto;
    background-color: #EAE9D7;
}

演示:
http://jsfiddle.net/nottrobin/qnRgL/

这个解决方案的一个警告是,它将隐藏溢出的内容。如果您需要显示溢出的内容,请尝试替代解决方案。


替代清算解决方案

如果因任何原因更改overflow属性导致问题,则另一种解决方案是使用:after伪元素添加生成的内容。 E.g:

.formRow:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
    background-color: #EAE9D7;
}

Generating Content Through CSS下:
http://robertnyman.com/2007/04/12/how-to-clear-css-floats-without-extra-markup-different-techniques-explained/

但请注意,此解决方案在IE 6和7中不起作用。