IT박스

부동 DIV가 다른 부동 DIV의 높이와 일치하도록 어떻게 강제 할 수 있습니까?

itboxs 2020. 11. 10. 07:56
반응형

부동 DIV가 다른 부동 DIV의 높이와 일치하도록 어떻게 강제 할 수 있습니까?


내 HTML 코드는 페이지를 각각 65 %, 35 %의 두 열로 나누고 있습니다.

<div style="float : left; width :65%; height:auto;background-color:#FDD017;">
   <div id="response">
   </div> 
</div>
<div style="float : left; width :35%;height:auto; background-color:#FDD017;">
   <div id="note">
   </div>
</div> 

에는 response div가변 데이터가 있습니다. note div, 나는 데이터를 해결했습니다. div두 개의 서로 다른 데이터 세트가 있더라도 배경색이 둘 다를 포함하는 상자를 채우는 것처럼 보이도록 동일한 높이로 표시해야합니다. 당연히 문제는 response div현재 표시되는 데이터의 양에 따라 높이가 달라지기 때문에입니다.

두 열의 높이가 항상 같은지 어떻게 확인할 수 있습니까?


배경색이 적용된 포함 div로 감싸고 '열'뒤에 지우기 div가 있습니다.

<div style="background-color: yellow;">
  <div style="float: left;width: 65%;">column a</div>
  <div style="float: right;width: 35%;">column b</div>
  <div style="clear: both;"></div>
</div>

일부 의견과 내 생각을 다루기 위해 업데이트되었습니다.

이 방법은 본질적으로 문제를 단순화하기 때문에 작동합니다.이 다소 'oldskool'방법에서는 두 개의 열을 넣은 다음 빈 지우기 요소를 입력합니다. 지우기 요소의 역할은 부모에게 (배경으로) 이것이 어디에 있는지 알려주는 것입니다. 플로팅 동작이 종료되면 부모가 기본적으로 클리어 위치에 0 픽셀의 높이를 렌더링 할 수 있으며, 이는 이전에 가장 높은 플로팅 요소가 무엇이든 상관 없습니다.

그 이유는 부모 요소의 높이가 가장 높은 열과 같은지 확인한 다음 부모에 배경이 설정되어 두 열의 높이가 같은 모양을 제공하기 때문입니다.

이 기술이 주목해야한다 'oldskool'더 나은 선택이 같은이 높이 계산 동작을 트리거 할 수 있기 때문에 clearfix 하거나 오버 플로우 가짐으로써 : 부모 요소에 숨겨져 있습니다.

이 제한된 시나리오에서 작동하지만 각 열이 시각적으로 다르게 보이거나 열 사이에 간격이있는 경우 부모 요소에 배경을 설정하는 것은 작동하지 않지만이 효과를 얻는 방법이 있습니다.

트릭은 모든 열에 하단 패딩을 추가하는 것입니다. 가장 짧은 열과 가장 큰 열의 차이가 될 것으로 예상되는 최대 크기로,이 문제를 해결할 수없는 경우 큰 숫자를 선택하고 다음을 추가해야합니다. 같은 숫자의 음의 하단 여백.

상위 개체에 숨겨진 오버플로가 필요하지만 결과는 각 열이 여백에서 제안한이 추가 높이를 렌더링하도록 요청하지만 실제로는 해당 크기의 레이아웃을 요청하지 않습니다 (음수 여백이 계산을 카운터하기 때문).

이렇게하면 부모가 가장 높은 열의 크기로 렌더링되고 모든 열이 해당 높이 + 사용 된 하단 패딩의 크기로 렌더링 될 수 있습니다.이 높이가 부모보다 크면 나머지는 단순히 잘립니다.

<div style="overflow: hidden;">
  <div style="background: blue;float: left;width: 65%;padding-bottom: 500px;margin-bottom: -500px;">column a<br />column a</div>
  <div style="background: red;float: right;width: 35%;padding-bottom: 500px;margin-bottom: -500px;">column b</div>
</div>

bowers 및 wilkins 웹 사이트 에서이 기법의 예를 볼 수 있습니다 (페이지 하단에있는 4 개의 수평 스포트라이트 이미지 참조).


열 효과를 만들기 위해 부동 div가 다른 div와 일치하도록 강제하려는 경우 이것이 제가하는 일입니다. 간단하고 깔끔해서 좋아요.

<div style="background-color: #CCC; width:300px; overflow:hidden; ">
    <!-- Padding-Bottom is equal to 100% of the container's size, Margin-bottom hides everything beyond
         the container equal to the container size. This allows the column to grow with the largest
         column. -->
    <div style="float: left;width: 100px; background:yellow; padding-bottom:100%; margin-bottom:-100%;">column a</div>
    <div style="float: left;width: 100px;  background:#09F;">column b<br />Line 2<br />Line 3<br />Line 4<br />Line 5</div>
    <div style="float:left; width:100px; background: yellow; padding-bottom:100%; margin-bottom:-100%;">Column C</div>
    <div style="clear: both;"></div>
</div>

나는 이것이 의미가 있다고 생각한다. 동적 콘텐츠에서도 잘 작동하는 것 같습니다.


다음은 여러 div의 높이를 동일하게 설정 하는 jQuery 플러그인 입니다. 그리고 아래는 플러그인의 실제 코드입니다.

$.fn.equalHeights = function(px) {
$(this).each(function(){
var currentTallest = 0;
$(this).children().each(function(i){
    if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
        });
    if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
        // for ie6, set height since min-height isn't supported
    if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
        $(this).children().css({'min-height': currentTallest}); 
    });
    return this;
};

이 문제에 대한 올바른 해결책은 display: table-cell

중요 :이 솔루션은 이미 동일한 컨테이너에서 다른 요소와 정렬되는 요소로 변환 float되므로 필요하지 않습니다 . 그것은 또한 당신이 수레, 오버플로, 배경이 빛나고 해킹이 파티에 가져다 주는 기타 모든 불쾌한 놀라움을 지우는 것에 대해 걱정할 필요가 없음을 의미합니다 .table-celldivfloat

CSS :

.container {
  display: table;
}
.column {
  display: table-cell;
  width: 100px;
}

HTML :

<div class="container">
    <div class="column">Column 1.</div>
    <div class="column">Column 2 is a bit longer.</div>
    <div class="column">Column 3 is longer with lots of text in it.</div>
</div>

관련 :


float가없는 div로 래핑해야합니다.

<div style="float:none;background:#FDD017;" class="clearfix">
    <div id="response" style="float:left; width:65%;">Response with two lines</div>
    <div id="note" style="float:left; width:35%;">single line note</div>
</div>

또한 여기 http://www.webtoolkit.info/css-clearfix.html 에서 clearfix 패치를 사용합니다 .


30 초 만에 2 열 테이블을 코딩하고 문제를 해결할 수 있는데 왜이 문제가 바닥에 닥치는 지 이해할 수 없습니다.

이 div 열 높이 문제는 일반적인 레이아웃 전체에서 발생합니다. 평범한 오래된 기본 HTML 태그로 스크립트를 작성하는 이유는 무엇입니까? 레이아웃에 거대하고 많은 테이블이 있지 않는 한, 테이블이 상당히 느리다는 주장을하지는 않습니다.


Flex는 기본적으로이 작업을 수행합니다.

<div id="flex">
 <div id="response">
 </div> 
 <div id="note">
 </div>
</div>   

CSS :

#flex{display:flex}
#response{width:65%}
#note{width:35%}

https://jsfiddle.net/784pnojq/1/

보너스 : 여러 행

https://jsfiddle.net/784pnojq/2/


원하는 배경색으로 외부 div에 둘 다 감싸는 것이 좋습니다.


언제든지 배경 이미지를 사용할 수 있습니다. 유일한 다른 완벽한 솔루션은 Jquery 옵션이므로이 옵션에 대해 100 % 투표하는 경향이 있습니다.

As with using the outer div with a background color you'll end up having to have the content in both divs reaching the same height.


This code will let you have a variable number of rows (with a variable number of DIVs on each row) and it will make all of the DIVs on each row match the height of its tallest neighbour:

If we assumed all the DIVs, that are floating, are inside a container with the id "divContainer", then you could use the following:

$(document).ready(function() {

var currentTallest = 0;
var currentRowStart = 0;
var rowDivs = new Array();

$('div#divContainer div').each(function(index) {

    if(currentRowStart != $(this).position().top) {

        // we just came to a new row.  Set all the heights on the completed row
        for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) rowDivs[currentDiv].height(currentTallest);

        // set the variables for the new row
        rowDivs.length = 0; // empty the array
        currentRowStart = $(this).position().top;
        currentTallest = $(this).height();
        rowDivs.push($(this));

    } else {

        // another div on the current row.  Add it to the list and check if it's taller
        rowDivs.push($(this));
        currentTallest = (currentTallest < $(this).height()) ? ($(this).height()) : (currentTallest);

    }
    // do the last row
    for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) rowDivs[currentDiv].height(currentTallest);

});
});

Having had the same sort of problem as well, requiring three divs next to each other with different content, with right-borders to 'seperate' them, the only solution that worked was a slightly modified version of the jQuery option in another answer. Remember you also need the script found here.

Below is my slightly modified version of the script, which just allows for a true min-height setting (as I needed my boxes to be at least a certain height).

/*--------------------------------------------------------------------
 * JQuery Plugin: "EqualHeights"
 * by:    Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
 *
 * Copyright (c) 2008 Filament Group
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Description:   Compares the heights or widths of the top-level children of a provided element
                  and sets their min-height to the tallest height (or width to widest width). Sets in em units
                  by default if pxToEm() method is available.
 * Dependencies: jQuery library, pxToEm method    (article:
                  http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)
 * Usage Example: $(element).equalHeights();
                  Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
                  Optional: to specify an actual min-height (in px), pass an integer value, regardless of previous parameter: $(element).equalHeights(false,150);
 * Version: 2.0, 08.01.2008
--------------------------------------------------------------------*/

$.fn.equalHeights = function(px,minheightval) {
    $(this).each(function(){
        if (minheightval != undefined) { 
            var currentTallest = minheightval;    
        } 
        else { 
            var currentTallest = 0;
        }
        $(this).children().each(function(i){
            if ($(this).height() > currentTallest) { 
                currentTallest = $(this).height();
            }
        });
        if (!px || !Number.prototype.pxToEm) 
            currentTallest = currentTallest.pxToEm(); //Use ems unless px is specified.
        // For Internet Explorer 6, set height since min-height isn't supported.
        if ($.browser.msie && $.browser.version == 6.0) { 
            $(this).children().css({'height': currentTallest});
        }
        $(this).children().css({'min-height': currentTallest});
    });
    return this;
};

It works like a charm and doesn't slow anything down :)

참고URL : https://stackoverflow.com/questions/526294/how-might-i-force-a-floating-div-to-match-the-height-of-another-floating-div

반응형