CSS:包含 div 的自动高度,包含 div 的背景 div 上的 100% 高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2779554/
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 22:01:35  来源:igfitidea点击:

CSS: auto height on containing div, 100% height on background div inside containing div

cssheight

提问by lukewm

The problem, is that I have a content div which stretches its container height-wise (container and content div have auto height).

问题是,我有一个内容 div,它会沿高度方向拉伸其容器(容器和内容 div 具有自动高度)。

I want the background container, which is a sibling div of the content div to stretch to fill the container. The background container contains divs to break the background into chunks.

我想要背景容器,它是内容 div 的兄弟 div 拉伸以填充容器。背景容器包含用于将背景分成块的 div。

The background and container divs have 100% width, the content container doesn't.

背景和容器 div 具有 100% 宽度,内容容器没有。

HTML:

HTML:

<div id="container">  
    <div id="content">  
        Some long content here ..  
    </div>  
     <div id="backgroundContainer">  
         <div id="someDivToShowABackground"/>  
         <div id="someDivToShowAnotherBackground"/>  
    </div>  
</div>

CSS:

CSS:

#container {
    height:auto;
    width:100%;
}

#content {
    height: auto;
    width:500px;
    margin-left:auto;
    margin-right:auto;
}

#backgroundContainer {
    height:100%;??? I want this to be the same height as container, but 100% makes it the height of the viewport.
}

回答by andreihondrari

In 2018 a lot of browsers support the Flexboxand Gridwhich are very powerful CSS display modes that overshine classical methods such as Faux Columns or Tabular Displays (which are treated later in this answer).

在 2018 年,许多浏览器都支持FlexboxGrid,它们是非常强大的 CSS 显示模式,它们超越了仿列或表格显示等经典方法(本答案稍后会对其进行处理)。

In order to implement this with the Grid, it is enough to specify display: gridand grid-template-columnson the container. The grid-template-columnsdepends on the number of columns you have, in this example I will use 3 columns, hence the property will look: grid-template-columns: auto auto auto, which basically means that each of the columns will have auto width.

为了用 Grid 实现这一点,在容器上指定display: gridgrid-template-columns就足够了。该网格模板列取决于你有列,在这个例子中,我将使用3列的数目,因此酒店将看:网格模板列:汽车汽车汽车,这基本上意味着,每列将有自动宽度。

Full working example with Grid:

网格的完整工作示例:

html, body {
    padding: 0;
    margin: 0;
}

.grid-container {
    display: grid;
    grid-template-columns: auto auto auto;
    width: 100%;
}

.grid-item {
    padding: 20px;
}

.a {
    background-color: DarkTurquoise;
}

.b {
    background-color: LightSalmon;
}

.c {
    background-color: LightSteelBlue;
}
<!DOCTYPE html>
<html>
<head>
    <title>Three Columns with Grid</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

    <div class="grid-container">
        <div class="grid-item a">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta.</p>
        </div>
        <div class="grid-item b">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta. Donec commodo elit mattis, bibendum turpis eu, malesuada nunc. Vestibulum sit amet dui tincidunt, mattis nisl et, tincidunt eros. Vivamus eu ultrices sapien. Integer leo arcu, lobortis sed tellus in, euismod ultricies massa. Mauris gravida quis ligula nec dignissim. Proin elementum mattis fringilla. Donec id malesuada orci, eu aliquam ipsum. Vestibulum fermentum elementum egestas. Quisque sit amet tempor mi.</p>
        </div>
        <div class="grid-item c">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis.</p>
        </div>
    </div>
</body>
</html>

Another way would be to use the Flexbox by specifying display: flexon the container of the columns, and giving the columns a relevant width. In the example that I will be using, which is with 3 columns, you basically need to split 100% in 3, so it's 33.3333% (close enough, who cares about 0.00003333... which isn't visible anyway).

另一种方法是通过在列的容器上指定display: flex并为列提供相关宽度来使用 Flexbox 。在我将使用的包含 3 列的示例中,您基本上需要将 100% 拆分为 3,因此它是 33.3333%(足够接近,谁在乎 0.00003333...无论如何都看不到)。

Full working example using Flexbox:

使用 Flexbox 的完整工作示例:

html, body {
    padding: 0;
    margin: 0;
}

.flex-container {
    display: flex;
    width: 100%;
}

.flex-column {
    padding: 20px;
    width: 33.3333%;
}

.a {
    background-color: DarkTurquoise;
}

.b {
    background-color: LightSalmon;
}

.c {
    background-color: LightSteelBlue;
}
<!DOCTYPE html>
<html>
<head>
    <title>Three Columns with Flexbox</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

    <div class="flex-container">
        <div class="flex-column a">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta.</p>
        </div>
        <div class="flex-column b">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta. Donec commodo elit mattis, bibendum turpis eu, malesuada nunc. Vestibulum sit amet dui tincidunt, mattis nisl et, tincidunt eros. Vivamus eu ultrices sapien. Integer leo arcu, lobortis sed tellus in, euismod ultricies massa. Mauris gravida quis ligula nec dignissim. Proin elementum mattis fringilla. Donec id malesuada orci, eu aliquam ipsum. Vestibulum fermentum elementum egestas. Quisque sit amet tempor mi.</p>
        </div>
        <div class="flex-column c">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis.</p>
        </div>
    </div>
</body>
</html>

The Flexbox and Grid are supported by all major browsers since 2017/2018, fact also confirmed by caniuse.com: Can I use grid, Can I use flex.

自 2017/2018 年以来,所有主要浏览器都支持 Flexbox 和 Grid,事实也由 caniuse.com 证实:我可以使用 grid我可以使用 flex

There are also a number of classical solutions, used before the age of Flexbox and Grid, like OneTrueLayout Technique, Faux Columns Technique, CSS Tabular Display Techniqueand there is also a Layering Technique.

还有一些经典的解决方案,在 Flexbox 和 Grid 时代之前使用,如OneTrueLayout TechniqueFaux Columns TechniqueCSS Tabular Display TechniqueLayering Technique

I do not recommend using these methods for they have a hackish nature and are not so elegant in my opinion, but it is good to know them for academic reasons.

我不建议使用这些方法,因为它们具有黑客性质并且在我看来不是那么优雅,但是出于学术原因了解它们是很好的。

A solution for equally height-ed columns is the CSS Tabular Display Techniquethat means to use the display:tablefeature. It works for Firefox 2+, Safari 3+, Opera 9+and IE8.

等高列的解决方案是CSS 表格显示技术,这意味着使用display:table功能。它适用于Firefox 2+Safari 3+Opera 9+IE8

The code for the CSS Tabular Display:

CSS 表格显示的代码:

#container {
  display: table;
  background-color: #CCC;
  margin: 0 auto;
}

.row {
  display: table-row;
}

.col {
  display: table-cell;
}

#col1 {
  background-color: #0CC;
  width: 200px;
}

#col2 {
  background-color: #9F9;
  width: 300px;
}

#col3 {
  background-color: #699;
  width: 200px;
}
<div id="container">
  <div id="rowWraper" class="row">
    <div id="col1" class="col">
      Column 1<br />Lorem ipsum<br />ipsum lorem
    </div>
    <div id="col2" class="col">
      Column 2<br />Eco cologna duo est!
    </div>
    <div id="col3" class="col">
      Column 3
    </div>
  </div>
</div>

Even if there is a problem with the auto-expanding of the width of the table-cell it can be resolved easy by inserting another div withing the table-cell and giving it a fixed width. Anyway, the over-expanding of the width happens in the case of using extremely long words (which I doubt anyone would use a, let's say, 600pxlong word) or some div's who's width is greater than the table-cell's width.

即使表格单元格宽度的自动扩展存在问题,也可以通过在表格单元格中插入另一个 div 并为其提供固定宽度来轻松解决。无论如何,在使用极长的单词(我怀疑有人会使用600px长的单词)或某些宽度大于表格单元格宽度的 div 的情况下,会发生宽度的过度扩展。

The Faux Column Techniqueis the most popular classical solution to this problem, but it has some drawbacks such as, you have to resize the background tiled image if you want to resize the columns and it is also not an elegant solution.

仿柱技术是目前最流行的经典解决了这个问题,但它也有一些缺点,例如,你如果要调整列来调整背景平铺图像,它也不是一个完美的解决方案。

The OneTrueLayout Techniqueconsists of creating a padding-bottom of an extreme big height and cut it out by bringing the real border position to the "normal logical position" by applying a negative margin-bottomof the same huge value and hiding the extent created by the padding with overflow: hiddenapplied to the content wraper. A simplified example would be:

OneTrueLayout技术包括创建一个极端的大高度的填充,底部,通过施加负削减它通过将真实的边界位置,以“正常逻辑位置”的下边距相同的巨大价值和隐藏所创造的程度带有溢出的填充:隐藏应用于内容包装器。一个简化的例子是:

Working example:

工作示例:

.wraper {
    overflow: hidden; /* This is important */
}

.floatLeft {
    float: left;
}

.block {
    padding-left: 20px;
    padding-right: 20px;
    padding-bottom: 30000px; /* This is important */
    margin-bottom: -30000px; /* This is important */
    width: 33.3333%;
    box-sizing: border-box; /* This is so that the padding right and left does not affect the width */
}

.a {
    background-color: DarkTurquoise;
}

.b {
    background-color: LightSalmon;
}

.c {
    background-color: LightSteelBlue;
}
<html>
<head>
  <title>OneTrueLayout</title>
</head>
<body>
    <div class="wraper">
        <div class="block floatLeft a">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis.</p>
        </div>
        <div class="block floatLeft b">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis. Duis mattis diam vitae tellus ornare, nec vehicula elit luctus. In auctor urna ac ante bibendum, a gravida nunc hendrerit. Praesent sed pellentesque lorem. Nam neque ante, egestas ut felis vel, faucibus tincidunt risus. Maecenas egestas diam massa, id rutrum metus lobortis non. Sed quis tellus sed nulla efficitur pharetra. Fusce semper sapien neque. Donec egestas dolor magna, ut efficitur purus porttitor at. Mauris cursus, leo ac porta consectetur, eros quam aliquet erat, condimentum luctus sapien tellus vel ante. Vivamus vestibulum id lacus vel tristique.</p>
        </div>
        <div class="block floatLeft c">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis. Duis mattis diam vitae tellus ornare, nec vehicula elit luctus. In auctor urna ac ante bibendum, a gravida nunc hendrerit.</p>
        </div>
    </div>
</body>
</html>

The Layering Techniquemust be a very neat solution that involves absolute positioning of div's withing a main relative positioned wrapper div. It basically consists of a number of child divs and the main div. The main div has imperatively position: relativeto it's css attribute collection. The children of this div are all imperatively position:absolute. The children must have topand bottomset to 0and left-rightdimensions set to accommodate the columns with each another. For example if we have two columns, one of width 100pxand the other one of 200px, considering that we want the 100px in the left side and the 200pxin the right side, the left column must have {left: 0; right: 200px}and the right column {left: 100px; right: 0;}

分层技术必须是一个非常整洁的解决方案,涉及的div的withing主相对定位的包装DIV绝对定位。它基本上由一些子 div 和主 div 组成。主 div 具有强制位置:相对于它的 css 属性集合。这个 div 的孩子都是命令式的position:absolute。子项必须将顶部底部设置为0,并将左右尺寸设置为彼此容纳列。例如,如果我们有两列,一列宽度为100px,另一列宽度为200px,考虑到我们想要左边的100px,右边的200px,左列必须有{left: 0; right: 200px}和右列{left: 100px; 右:0;}

In my opinion the unimplemented 100% height within an automated height container is a major drawback and the W3C should consider revising this attribute (which since 2018 is solvable with Flexbox and Grid).

在我看来,自动高度容器内未实现的 100% 高度是一个主要缺点,W3C 应该考虑修改这个属性(自 2018 年以来可以通过 Flexbox 和 Grid 解决)。

Other resources: link1, link2, link3, link4, link5 (important)

其他资源:link1link2link3link4link5(重要)

回答by Michael Antonius

Make #containerto display:inline-block

#containerdisplay:inline-block

#container {
  height: auto;
  width: 100%;
  display: inline-block;
}

#content {
  height: auto;
  width: 500px;
  margin-left: auto;
  margin-right: auto;
}

#backgroundContainer {
  height: 200px; /*200px is example, change to what you want*/
  width: 100%;
}

Also see: W3Schools

另见:W3Schools

回答by Gabriel

Okay so someone is probably going to slap me for this answer, but I use jQuery to solve all my irritating problems and it turns out that I just used something today to fix a similar issue. Assuming you use jquery:

好的,所以有人可能会因为这个答案而扇我耳光,但我使用 jQuery 来解决我所有恼人的问题,结果我今天刚刚使用了一些东西来解决类似的问题。假设您使用 jquery:

$("#content").sibling("#backgroundContainer").css("height",$("#content").outerHeight());

this is untested but I think you can see the concept here. Basically after it is loaded, you can get the height (outerHeight includes padding + borders, innerHeight for the content only). Hope that helps.

这是未经测试的,但我认为您可以在这里看到这个概念。基本上在加载后,您可以获得高度(outerHeight 包括填充 + 边框,innerHeight 仅用于内容)。希望有帮助。

Here is how you bind it to the window resize event:

以下是将其绑定到窗口调整大小事件的方法:

$(window).resize(function() {
  $("#content").sibling("#backgroundContainer").css("height",$("#content").outerHeight());
});

回答by Tim

Somewhere you will need to set a fixed height, instead of using auto everywhere. You will find that if you set a fixed height on your content and/or container, then using auto for things inside it will work.

在某个地方你需要设置一个固定的高度,而不是在任何地方使用 auto。你会发现,如果你在你的内容和/或容器上设置了一个固定的高度,那么对里面的东西使用 auto 就可以了。

Also, your boxes will still expand height-wise with more content in, even though you have set a height for it - so don't worry about that :)

此外,即使您已为其设置了高度,您的盒子仍会在高度方面扩展并包含更多内容 - 所以不要担心:)

#container {
  height:500px;
  min-height:500px;
}

回答by Wex

You shouldn't have to set height: 100%at any point if you want your container to fill the page. Chances are, your problem is rooted in the fact that you haven't cleared the floats in the container's children. There are quite a few ways to solve this problem, mainly adding overflow: hiddento the container.

height: 100%如果您希望容器填满页面,则不必在任何时候进行设置。很有可能,您的问题的根源在于您尚未清除容器子项中的浮点数。解决这个问题的方法很多,主要是添加overflow: hidden到容器中。

#container { overflow: hidden; }

Should be enough to solve whatever height problem you're having.

应该足以解决您遇到的任何身高问题。

回答by imos

Just a quick note because I had a hard time with this.

只是一个简短的说明,因为我很难做到这一点。

By using #container { overflow: hidden; } the page I had started to have layout issues in Firefox and IE (when the zoom would go in and out the content would bounce in and out of the parent div).

通过使用 #container { 溢出:隐藏;我开始在 Firefox 和 IE 中出现布局问题的页面(当缩放进出时,内容会在父 div 中进出)。

The solution to this issue is to add a display: inline-block; to the same div with overflow:hidden;

这个问题的解决办法是添加一个display:inline-block; 到同一个 div 溢出:隐藏;

回答by Vijay

Try excluding height from the style element.

尝试从样式元素中排除高度。

i.e. neither give height:100% nor to any other value.

即既不给 height:100% 也不给任何其他值。

回答by Jangli Coder

{
    height:100vh;
    width:100vw;
}

回答by Gregws

I ended up making 2 display:table;

我最终制作了 2 个 display:table;

#container-tv { /* Tiled background */
    display:table;
    width:100%;
    background-image: url(images/back.jpg);
    background-repeat: repeat;  
}
#container-body-background { /* center column but not 100% width */ 
    display:table;
    margin:0 auto;
    background-image:url(images/middle-back.png);
    background-repeat: repeat-y;

}

This made it have a tiled background image with a background image in the middle as a column. It stretches to 100% height of page not just 100% of browser window size

这使得它有一个平铺的背景图像,中间有一个背景图像作为一列。它延伸到 100% 的页面高度,而不仅仅是 100% 的浏览器窗口大小