Programing

CSS : 높이를 지정하지 않고 두 요소를 서로 위에 배치하는 방법은 무엇입니까?

lottogame 2020. 10. 17. 08:58
반응형

CSS : 높이를 지정하지 않고 두 요소를 서로 위에 배치하는 방법은 무엇입니까?


정확히 서로 위에 배치해야하는 두 개의 DIV가 있습니다. 그러나 그렇게하면 포함 DIV가 높이가없는 것처럼 작동하기 때문에 서식이 모두 망가집니다. 나는 이것이 예상되는 동작이라고 생각 position:absolute하지만이 두 요소를 서로 위에 배치하고 콘텐츠가 늘어남에 따라 컨테이너가 늘어나도록하는 방법을 찾아야합니다.

의 왼쪽 상단 가장자리는의 왼쪽 상단 가장자리에 .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;
}

우선, 절대적으로 배치 된 요소에 대한 위치를 포함해야합니다. 그렇지 않으면 이상하고 혼란스러운 행동을 보게 될 것입니다. top: 0; left: 0절대적으로 배치 된 두 요소 모두에 대해 CSS에 추가하고 싶을 것입니다 . 당신은 또한이 할 수 있습니다 position: relative.container_row당신이 절대 위치 요소를 배치 할 것인지 가 아니라 문서의 몸보다 더 상위에 관하여 :

요소에 '위치 : 절대'가있는 경우 '위치'가 '절대', '상대'또는 '고정'인 가장 가까운 조상이 포함하는 블록을 설정합니다.

문제는 position: absolute정상적인 흐름에서 요소제거 한다는 것입니다 .

일반 흐름에서 완전히 제거됩니다 (나중의 형제에 영향을주지 않음). 절대적으로 배치 된 상자는 정상 흐름 자식과 절대적으로 (고정되지 않은) 배치 된 후손에 대한 새 포함 블록을 설정합니다. 그러나 절대 위치 요소의 내용은 다른 상자 주위로 흐르지 않습니다.

즉, 절대 위치 요소는 부모 요소의 크기에 영향을 미치지 않으며 첫 번째 요소의 <div class="container_row">높이는 0입니다.

따라서 높이가 얼마나 될지 (또는 동등하게 높이를 지정할 수 있음) 알지 못하는 한 절대 위치에있는 요소로하려는 작업을 수행 할 수 없습니다. 높이를 지정할 수 있다면에 동일한 높이를 지정할 수 .container_row있으며 모든 것이 정렬됩니다. 절대적으로 배치 된 요소를위한 공간을 남겨두기 margin-top위해 두 번째 에을 넣을 수도 있습니다 .container_row. 예를 들면 :

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


실제로 이것은 위치 absolute와 높이 지정 없이 가능합니다 . 해야 할 일은 display: grid부모 요소를 사용 하고 하위 요소를 동일한 행과 열에 넣는 것입니다.

귀하의 HTML을 기반으로 아래 예를 확인하십시오. <span>몇 가지 색상 만 추가 했으므로 결과를 볼 수 있습니다.

또한 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>


좋은 대답은 "mu is too short"입니다. 나는 똑같은 것을 찾고 있었고 귀하의 게시물을 읽은 후 내 문제에 맞는 해결책을 찾았습니다.

나는 정확히 같은 크기의 두 요소를 가지고 있었고 그것들을 쌓고 싶었습니다. 각각 크기가 같기 때문에 제가 할 수있는 것은

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

마지막 요소에만. 이렇게하면 첫 번째 요소가 올바르게 삽입되어 상위 높이를 "밀고"두 번째 요소가 맨 위에 배치됩니다.

이것이 같은 (알 수없는) 높이로 2 개 이상의 요소를 쌓으려는 다른 사람들에게 도움이되기를 바랍니다.


나는 설정해야했다

Container_height = Element1_height = Element2_height

.Container {
    position: relative;
}

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

.ElementOne {
    position:absolute;
}

.ElementTwo{
    position:absolute;
}

Z- 색인을 사용하여 맨 위에있을 항목을 설정할 수 있습니다.


Here's another solution using display: flex instead of position: absolute or 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>


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.


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 div to 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%).

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


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

  • the container_row MUST have position: relative;
  • the children (...), MUST have position: absolute; left:0;
  • to make sure the children (...) align exactly over each other, the container_row should have additional styling:
    • height:x; line-height:x; vertical-align:middle;
    • text-align:center; could, also, help.

참고URL : https://stackoverflow.com/questions/6780614/css-how-to-position-two-elements-on-top-of-each-other-without-specifying-a-hei

반응형