CSS:如何在不指定高度的情况下将两个元素放在一起?

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

CSS: How to position two elements on top of each other, without specifying a height?

css

提问by Andrew

I have two DIVs that I need to position exactly on top of each other. However, when I do that, the formatting gets all screwed up because the containing DIV acts like there is no height. I think this is the expected behavior with position:absolutebut I need to find a way to position these two elements on top of each other and have the container stretch as the content stretches:

我有两个 DIV,我需要将它们准确地放在彼此的顶部。但是,当我这样做时,格式会全部搞砸,因为包含的 DIV 就像没有高度一样。我认为这是预期的行为,position:absolute但我需要找到一种方法将这两个元素放在彼此的顶部,并使容器随着内容的拉伸而拉伸:

The top left edge of .layer2should be exactly aligned to the top left edge of layer1

的左上边缘.layer2应与 的左上边缘完全对齐layer1

<!-- HTML -->
<div class="container_row">
    <div class="layer1">
        Lorem ipsum...
    </div>
    <div class="layer2">
        More lorem ipsum...
    </div>
</div>
<div class="container_row">
    ...same HTML as above. This one should never overlap the .container_row above.
</div>

/* CSS */
.container_row {}

.layer1 {
    position:absolute;
    z-index: 1;
}

.layer2 {
    position:absolute;
    z-index: 2;
}

采纳答案by mu is too short

First of all, you really should be including the position on absolutely positioned elements or you will come across odd and confusing behavior; you probably want to add top: 0; left: 0to the CSS for both of your absolutely positioned elements. You'll also want to have position: relativeon .container_rowif you want the absolutely positioned elements to be positioned with respect to their parent rather than the document's body:

首先,你真的应该在绝对定位的元素上包含位置,否则你会遇到奇怪和令人困惑的行为;您可能希望top: 0; left: 0为两个绝对定位的元素添加到 CSS 中。你也想拥有position: relative.container_row,如果你想绝对定位的元素被定位相对于他们的父母,而不是文档的身体

If the element has 'position: absolute', the containing block is established by the nearest ancestor with a 'position' of 'absolute', 'relative' or 'fixed' ...

如果元素具有“位置:绝对”,则包含块由最近的祖先建立,其“位置”为“绝对”、“相对”或“固定”......

Your problem is that position: absoluteremoves elements from the normal flow:

您的问题是position: absolute从正常流程删除元素

It is removed from the normal flow entirely (it has no impact on later siblings). An absolutely positioned box establishes a new containing block for normal flow children and absolutely (but not fixed) positioned descendants. However, the contents of an absolutely positioned element do not flow around any other boxes.

它完全从正常流程中删除(它对以后的兄弟姐妹没有影响)。一个绝对定位的盒子为正常流子和绝对(但不是固定)定位的后代建立一个新的包含块。但是,绝对定位元素的内容不会围绕任何其他框流动。

This means that absolutely positioned elements have no effect whatsoever on their parent element's size and your first <div class="container_row">will have a height of zero.

这意味着绝对定位的元素对其父元素的大小没有任何影响,并且您的第一个元素的<div class="container_row">高度为零。

So you can't do what you're trying to do with absolutely positioned elements unless you know how tall they're going to be (or, equivalently, you can specify their height). If you can specify the heights then you can put the same heights on the .container_rowand everything will line up; you could also put a margin-topon the second .container_rowto leave room for the absolutely positioned elements. For example:

因此,除非您知道它们将有多高(或者,等效地,您可以指定它们的高度),否则您无法对绝对定位的元素做您想做的事情。如果您可以指定高度,那么您可以在上面放置相同的高度.container_row,所有东西都会对齐;你也可以margin-top在第二个上放一个,.container_row为绝对定位的元素留出空间。例如:

http://jsfiddle.net/ambiguous/zVBDc/

http://jsfiddle.net/ambiguous/zVBDc/

回答by instead

Actually this is possible without position absoluteand specifying any height.All You need to do, is use display: gridon parent element and put descendants, into the same row and column.

实际上,这在没有位置absolute和指定任何高度的情况下是可能的。您需要做的就是display: grid在父元素上使用并将后代放入同一行和列中。

Please check example below, based on Your HTML. I added only <span>and some colors, so You can see the result.

请根据您的 HTML 检查下面的示例。我只添加了<span>一些颜色,所以你可以看到结果。

You can also easily change z-indexeach of descendant elements, to manipulate its visibility (which one should be on top).

您还可以轻松更改z-index每个后代元素,以操纵其可见性(哪个应该在顶部)。

.container_row{
  display: grid;
}

.layer1, .layer2{
  grid-column: 1;
  grid-row: 1;
}

.layer1 span{
  color: #fff;
  background: #000cf6;
}

.layer2{
  background: rgba(255, 0, 0, 0.4);
}
<div class="container_row">
    <div class="layer1">
        <span>Lorem ipsum...<br>Test test</span>
    </div>
    <div class="layer2">
        More lorem ipsum...
    </div>
</div>
<div class="container_row">
    ...same HTML as above. This one should never overlap the .container_row above.
</div>

回答by kraenhansen

Great answer, "mu is too short". I was seeking the exact same thing, and after reading your post I found a solution that fitted my problem.

很好的答案,“mu 太短了”。我正在寻找完全相同的东西,在阅读了您的帖子后,我找到了一个适合我的问题的解决方案。

I was having two elements of the exact same size and wanted to stack them. As each have same size, what I could do was to make

我有两个完全相同大小的元素,想要堆叠它们。由于每个都有相同的尺寸,我能做的就是制作

position: absolute;
top: 0px;
left: 0px;

on only the last element. This way the first element is inserted correctly, "pushing" the parents height, and the second element is placed on top.

仅在最后一个元素上。这样第一个元素被正确插入,“推动”父元素的高度,第二个元素被放置在顶部。

Hopes this helps other people trying to stacking 2+ elements with same (unknown) height.

希望这可以帮助其他人尝试堆叠具有相同(未知)高度的 2+ 个元素。

回答by Cornelius

Here's another solution using display: flex instead of position: absolute or display: grid.

这是使用 display: flex 而不是 position: absolute 或 display: grid 的另一种解决方案。

.container_row{
  display: flex;
}

.layer1 {
  width: 100%;
  background-color: rgba(255,0,0,0.5);  // red
}

.layer2{
  width: 100%;
  margin-left: -100%;
  background-color: rgba(0,0,255,0.5);  // blue
}
<div class="container_row">
    <div class="layer1">
        <span>Lorem ipsum...</span>
    </div>
    <div class="layer2">
        More lorem ipsum...
    </div>
</div>
<div class="container_row">
    ...same HTML as above. This one should never overlap the .container_row above.
</div>

回答by Arun Prasad E S

I had to set

我必须设置

Container_height = Element1_height = Element2_height

容器高度 = 元素 1_高度 = 元素 2_高度

.Container {
    position: relative;
}

.ElementOne, .Container ,.ElementTwo{
    width: 283px;
    height: 71px;
}

.ElementOne {
    position:absolute;
}

.ElementTwo{
    position:absolute;
}

Use can use z-index to set which one to be on top.

使用可以使用 z-index 来设置哪一个在最上面。

回答by Ken Mueller

Here's some reusable css that will preserve the height of each element without using position: absolute:

这是一些可重用的 css,它们将保留每个元素的高度而不使用position: absolute

.stack {
    display: grid;
}
.stack > * {
    grid-row: 1;
    grid-column: 1;
}

The first element in your stackis the background, and the second is the foreground.

你的第一个元素stack是背景,第二个是前景。

回答by Luiz Sócrate

Due to absolute positioning removing the elements from the document flow position: absolute is not the right tool for the job. Depending on the exact layout you want to create you will be successful using negative margins, position:relative or maybe even transform: translate. Show us a sample of what you want to do we can help you better.

由于绝对定位从文档流位置删除元素:绝对不是适合这项工作的工具。根据您要创建的确切布局,您将成功使用负边距、位置:相对或什至转换:翻译。向我们展示您想要做什么的示例,我们可以更好地帮助您。

回答by Luke Puplett

Of course, the problem is all about getting your height back. But how can you do that if you don't know the height ahead of time? Well, if you know what aspect ratio you want to give the container (and keep it responsive), you can get your height back by adding padding to another child of the container, expressed as a percentage.

当然,问题全在于让你的身高恢复。但是,如果您不提前知道高度,您怎么能做到这一点呢?好吧,如果你知道你想要给容器什么纵横比(并保持它的响应性),你可以通过向容器的另一个子项添加填充来恢复你的高度,以百分比表示。

You can even add a dummy divto the container and set something like padding-top: 56.25%to give the dummy element a height that is a proportion of the container's width. This will push out the container and give it an aspect ratio, in this case 16:9 (56.25%).

您甚至可以div向容器添加一个虚拟padding-top: 56.25%元素,并设置类似的内容,为虚拟元素设置一个与容器宽度成比例的高度。这将推出容器并为其指定纵横比,在本例中为 16:9 (56.25%)。

Padding and margin use the percentage of the width, that's really the trick here.

填充和边距使用宽度的百分比,这就是这里的诀窍。

回答by justaguestpassingby

After much testing, I have verified that the original question is already right; missing just a couple of settings:

经过多次测试,我验证了原来的问题已经正确;缺少几个设置:

  • the container_rowMUST have position: relative;
  • the children (...), MUST have position: absolute; left:0;
  • to make sure the children (...) align exactly over each other, the container_rowshould have additional styling:
    • height:x; line-height:x; vertical-align:middle;
    • text-align:center;could, also, help.
  • container_row必须有position: relative;
  • 孩子们(...),必须有 position: absolute; left:0;
  • 为了确保孩子 (...) 彼此完全对齐, container_row应该有额外的样式:
    • height:x; line-height:x; vertical-align:middle;
    • text-align:center;也可以提供帮助。