Html 如何让 div 调整其高度以适应容器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1230354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:28:35  来源:igfitidea点击:

How to get a div to resize its height to fit container?

htmlcss

提问by ParoX

How can I get the nav div to have expand down or have the height the same as its parent div?

如何让导航 div 向下扩展或具有与其父 div 相同的高度?

*   {
    border:0; 
    padding:0; 
    margin:0;
}
#container {
    margin-left: auto;
    margin-right: auto;
    border: 1px solid black;
    overflow: auto;
    width: 800px;   
}
#nav {
    width: 19%;
    border: 1px solid green;
    float:left; 
}
#content {
    width: 79%;
    border: 1px solid red;
    float:right;
}
<div id="container">
    <div id="nav">
        <ul>
            <li>Menu</li>
            <li>Menu</li>
            <li>Menu</li>
            <li>Menu</li>
            <li>Menu</li>
        </ul>
    </div>
    <div id="content">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam fermentum consequat ligula vitae posuere. Mauris dolor quam, consequat vel condimentum eget, aliquet sit amet sem. Nulla in lectus ac felis ultrices dignissim quis ac orci. Nam non tellus eget metus sollicitudin venenatis sit amet at dui. Quisque malesuada feugiat tellus, at semper eros mollis sed. In luctus tellus in magna condimentum sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur vel dui est. Aliquam vitae condimentum dui. Praesent vel mi at odio blandit pellentesque. Proin felis massa, vestibulum a hendrerit ut, imperdiet in nulla. Sed aliquam, dolor id congue porttitor, mauris turpis congue felis, vel luctus ligula libero in arcu. Pellentesque egestas blandit turpis ac aliquet. Sed sit amet orci non turpis feugiat euismod. In elementum tristique tortor ac semper.</p>
    </div>
</div>

回答by kmiyashiro

Simple Way

简单的方法

You can achieve this with setting both the topand bottomattributes of the nav to 0and the position: absolute. Set the container to position: relative.

你可以同时与设置实现这一目标topbottom资产净值的属性0position: absolute。将容器设置为position: relative.

See how this is done

看看这是怎么做的

Modern Way (Flexbox)

现代方式(弹性盒)

IE11+ and all modern browsers support flexbox.

IE11+ 和所有现代浏览器都支持 flexbox。

.container {
  display: flex;
  flex-direction: column;
}

.child {
  flex-grow: 1;
}

回答by schubySteve

you would possibbly need to specify the height of container and then set the nav's height to 100%.

您可能需要指定容器的高度,然后将导航的高度设置为 100%。

Edit: had a quick look around and it seems that the height property applies to the parents height so you will indeed need to set the containers height.

编辑:快速浏览一下,似乎高度属性适用于父高度,因此您确实需要设置容器高度。

NB: setting the height of the body element to 100% only scales it to the height of the browser window. Any content which goeds over one page will not have the same background etc.

注意:将 body 元素的高度设置为 100% 只会将其缩放到浏览器窗口的高度。任何超过一页的内容都不会具有相同的背景等。

回答by Hello World

I had the same issue, I resolved it using some javascript.

我有同样的问题,我使用一些 javascript 解决了它。

<script type="text/javascript">
 var theHeight = $("#PrimaryContent").height() + 100;
 $('#SecondaryContent').height(theHeight);
</script>

回答by Andrew Moore

Unfortunately, there is no fool-proof way of achieving this. A block will only expand to the height of its container if it is not floated. Floated blocks are considered outside of the document flow.

不幸的是,没有万无一失的方法来实现这一点。如果块没有浮动,它只会扩展到其容器的高度。浮动块被视为文档流之外。

One way to do the following without using JavaScript is via a technique called Faux-Columns.

在不使用 JavaScript 的情况下执行以下操作的一种方法是通过一种称为Faux-Columns的技术。

It basically involves applying a background-imageto the parent elements of the floated elements which makes you believe that the two elements are the same height.

它基本上涉及将 abackground-image应用于浮动元素的父元素,这使您相信这两个元素具有相同的高度。

More information available at:

更多信息请访问:

A List Apart: Articles: Faux Columns

A List Apart:文章:人造专栏

回答by Logesh Paul

Another one simple method is there. You don't need to code more in CSS. Just including a java script and entering the div "id" inside the script you can get equal height of columns so that you can have the height fit to container. It works in major browsers.

还有另一种简单的方法。您不需要在 CSS 中编写更多代码。只需包含一个java脚本并在脚本中输入div“id”,您就可以获得相等的列高度,以便您可以将高度适合容器。它适用于主要浏览器。

Source Code:

源代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title></title>
<style type="text/css">
*   {border:0; padding:0; margin:0;}/* Set everything to "zero" */
#container {
    margin-left: auto;
    margin-right: auto;
    border: 1px solid black;
    overflow: auto;
    width: 800px;       
}
#nav {
    width: 19%;
    border: 1px solid green;
    float:left; 
}
#content {
    width: 79%;
    border: 1px solid red;
    float:right;
}
</style>

<script language="javascript">
var ddequalcolumns=new Object()
//Input IDs (id attr) of columns to equalize. Script will check if each corresponding column actually exists:
ddequalcolumns.columnswatch=["nav", "content"]

ddequalcolumns.setHeights=function(reset){
var tallest=0
var resetit=(typeof reset=="string")? true : false
for (var i=0; i<this.columnswatch.length; i++){
if (document.getElementById(this.columnswatch[i])!=null){
if (resetit)
document.getElementById(this.columnswatch[i]).style.height="auto"
if (document.getElementById(this.columnswatch[i]).offsetHeight>tallest)
tallest=document.getElementById(this.columnswatch[i]).offsetHeight
}
}
if (tallest>0){
for (var i=0; i<this.columnswatch.length; i++){
if (document.getElementById(this.columnswatch[i])!=null)
document.getElementById(this.columnswatch[i]).style.height=tallest+"px"
}
}
}

ddequalcolumns.resetHeights=function(){
this.setHeights("reset")
}

ddequalcolumns.dotask=function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
if (target.addEventListener)
target.addEventListener(tasktype, functionref, false)
else if (target.attachEvent)
target.attachEvent(tasktype, functionref)
}

ddequalcolumns.dotask(window, function(){ddequalcolumns.setHeights()}, "load")
ddequalcolumns.dotask(window, function(){if (typeof ddequalcolumns.timer!="undefined") clearTimeout(ddequalcolumns.timer); ddequalcolumns.timer=setTimeout("ddequalcolumns.resetHeights()", 200)}, "resize")


</script>

<div id=container>
    <div id=nav>
        <ul>
                <li>Menu</li>
                <li>Menu</li>
                <li>Menu</li>
                <li>Menu</li>
                <li>Menu</li>
        </ul>
    </div>
    <div id=content>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam fermentum consequat ligula vitae posuere. Mauris dolor quam, consequat vel condimentum eget, aliquet sit amet sem. Nulla in lectus ac felis ultrices dignissim quis ac orci. Nam non tellus eget metus sollicitudin venenatis sit amet at dui. Quisque malesuada feugiat tellus, at semper eros mollis sed. In luctus tellus in magna condimentum sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur vel dui est. Aliquam vitae condimentum dui. Praesent vel mi at odio blandit pellentesque. Proin felis massa, vestibulum a hendrerit ut, imperdiet in nulla. Sed aliquam, dolor id congue porttitor, mauris turpis congue felis, vel luctus ligula libero in arcu. Pellentesque egestas blandit turpis ac aliquet. Sed sit amet orci non turpis feugiat euismod. In elementum tristique tortor ac semper.</p>
    </div>
</div>

</body>
</html>

You can include any no of divs in this script.

您可以在此脚本中包含任何 div。

ddequalcolumns.columnswatch=["nav", "content"]

ddequalcolumns.columnswatch=[“导航”,“内容”]

modify in the above line its enough.

在上面的行中修改就足够了。

Try this.

尝试这个。

回答by joeytwiddle

If the trick using position:absolute, position:relativeand top/left/bottom/right: 0pxis not appropriate for your situation, you could try:

如果招用position:absoluteposition:relative而且top/left/bottom/right: 0px不适合你的情况,你可以尝试:

#nav {
    height: inherit;
}

This worked on one of our pages, although I am not sure exactly what other conditions were needed for it to succeed!

这在我们的一个页面上有效,尽管我不确定它成功还需要哪些其他条件!

回答by Tyler Carter

You probably are going to want to use the following declaration:

您可能想要使用以下声明:

height: 100%;

height: 100%;

This will set the div's height to 100% of its containers height, which will make it fill the parent div.

这会将 div 的高度设置为其容器高度的 100%,这将使其填充父 div。

回答by Lasithds

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
#top, #bottom {
    height: 100px;
    width: 100%;
    position: relative;
}
#container {
    overflow: hidden;
    position: relative;
    width: 100%;
}
#container .left {
    height: 550px;
    width: 55%;
    position: relative;
    float: left;
    background-color: #3399FF;
}
#container .right {
    height: 100%;
    position: absolute;
    right: 0;
    left: 55%;
    bottom: 0px;
    top: 0px;
    background-color: #3366CC;
}
</style>
</head>

<body>
<div id="top"></div>
<div id="container">
  <div class="left"></div>
  <div class="right"></div>
</div>
<div id="bottom"></div>
</body>
</html>