使 div 高度等于其父级 (100%)
Make div height equal to its parent (100%)
我有一个包含另外两个 div 的主 div。我需要第一个必须具有与父级相同的高度 div。 CSS 中未指定父 div 身高。
这是一个例子:http://jsfiddle.net/x8dhnh4L/
粉红色 div 必须扩展到父级的全高(红色边框)。
我尝试的一个解决方案是使用 display:flex
,但它对 IE 不友好(我需要 IE8+ 兼容性)。另外,我只想用 CSS 来实现,所以我避免使用 JS。
http://jsfiddle.net/x8dhnh4L/1/
将边栏设置为
float:right;
并设置内容
height:100%;
您可以尝试使用 table 布局:
- 在 parent
上设置 display:table
设置 display:table-cell 给需要相同高度的孩子
#container {
position: relative;
width:600px;
border: 1px solid red;
display:table;
}
#content {
display: table-cell;
background-color:pink;
width:400px;
}
#side-bar {
display:table-cell;
background-color:yellow;
width:170px;
padding-left:25px;
vertical-align: top;
}
这是一个有效的 fiddle:
http://jsfiddle.net/x8dhnh4L/2/
如评论中所述,边距在具有 display:table-cell
的元素中不起作用。如果acceptable,你可以用padding-left
代替margin-left
...
您还可以添加一个额外的 <div>
以将 2 列分开 25px。
一个快速的解决方案是对 #container
使用 display:table
,对 #content
使用 height:100%
。
如果你真的想让“#content”div扩展到“#container”高度,你需要为parent div“#container”设置一个高度并且"#content"
的高度和浮动
#container {
position: relative;
width:600px;
border: 1px solid red;
height: 800px; //whatever height you need
}
#content {
display: inline-block;
background-color:pink;
width:400px;
height:100%;
float: left;
}
这样,“#content”高度将调整为“#container”高度,但“#side-bar”将采用显示其内容所需的高度。
使用 Hanoncs 解决方案,parent div“#container”将调整为 child 的 div“#content”高度。
一个简单的解决方法是在父元素上使用 display: table;
声明,在子元素上使用 display: table-cell;
声明。
我建议阅读 Equal Height Columns with Cross-Browser CSS and No Hacks。
希望对您有所帮助!
我有一个包含另外两个 div 的主 div。我需要第一个必须具有与父级相同的高度 div。 CSS 中未指定父 div 身高。
这是一个例子:http://jsfiddle.net/x8dhnh4L/ 粉红色 div 必须扩展到父级的全高(红色边框)。
我尝试的一个解决方案是使用 display:flex
,但它对 IE 不友好(我需要 IE8+ 兼容性)。另外,我只想用 CSS 来实现,所以我避免使用 JS。
http://jsfiddle.net/x8dhnh4L/1/
将边栏设置为
float:right;
并设置内容
height:100%;
您可以尝试使用 table 布局:
- 在 parent 上设置 display:table
设置 display:table-cell 给需要相同高度的孩子
#container { position: relative; width:600px; border: 1px solid red; display:table; } #content { display: table-cell; background-color:pink; width:400px; } #side-bar { display:table-cell; background-color:yellow; width:170px; padding-left:25px; vertical-align: top; }
这是一个有效的 fiddle: http://jsfiddle.net/x8dhnh4L/2/
如评论中所述,边距在具有 display:table-cell
的元素中不起作用。如果acceptable,你可以用padding-left
代替margin-left
...
您还可以添加一个额外的 <div>
以将 2 列分开 25px。
一个快速的解决方案是对 #container
使用 display:table
,对 #content
使用 height:100%
。
如果你真的想让“#content”div扩展到“#container”高度,你需要为parent div“#container”设置一个高度并且"#content"
的高度和浮动#container {
position: relative;
width:600px;
border: 1px solid red;
height: 800px; //whatever height you need
}
#content {
display: inline-block;
background-color:pink;
width:400px;
height:100%;
float: left;
}
这样,“#content”高度将调整为“#container”高度,但“#side-bar”将采用显示其内容所需的高度。
使用 Hanoncs 解决方案,parent div“#container”将调整为 child 的 div“#content”高度。
一个简单的解决方法是在父元素上使用 display: table;
声明,在子元素上使用 display: table-cell;
声明。
我建议阅读 Equal Height Columns with Cross-Browser CSS and No Hacks。
希望对您有所帮助!