prosource

부모 키를 지정하지 않고 자식 div를 부모 div 키의 100%로 강제하는 방법

probook 2023. 4. 8. 08:40
반응형

부모 키를 지정하지 않고 자식 div를 부모 div 키의 100%로 강제하는 방법

다음과 같은 구조를 가진 사이트가 있습니다.

<div id="header"></div>

<div id="main">
  <div id="navigation"></div>
  <div id="content"></div>
</div>

<div id="footer"></div>

네비게이션은 왼쪽에, 콘텐츠 div는 오른쪽에 있습니다.콘텐츠 div의 정보는 PHP를 통해 가져오기 때문에 매번 다릅니다.

로드되는 페이지에 관계없이 네비게이션의 높이가 컨텐츠 div의 높이와 같도록 하려면 어떻게 해야 합니까?

부모의 경우:

display: flex;

프리픽스 http://css-tricks.com/using-flexbox/ 를 추가해야 합니다.

@Adam Garner가 지적한 바와 같이 align-items: 스트레칭은 필요하지 않습니다.자녀용이 아닌 부모용이기도 합니다.아이 스트레칭을 정의하려면 align-self를 사용합니다.

.parent {
  background: red;
  padding: 10px;
  display:flex;
}

.other-child {
  width: 100px;
  background: yellow;
  height: 150px;
  padding: .5rem;
}

.child {  
  width: 100px;
  background: blue;
}
<div class="parent">
  <div class="other-child">
    Only used for stretching the parent
  </div>
  <div class="child"></div>
</div>

메모: 이 답변은 Flexbox 표준을 지원하지 않는 레거시 브라우저에 적용됩니다.최신 접근법에 대해서는http://https://stackoverflow.com/a/23300532/1155721 를 참조해 주세요.


크로스브라우저 CSS와 No Hacks를 사용한 등높이 컬럼을 살펴보시기 바랍니다.

기본적으로 CSS를 브라우저와 호환되는 방법으로 사용하는 것은 간단한 일이 아니라 테이블에서 간단한 일이기 때문에 사전에 패키지화된 적절한 솔루션을 찾을 수 있습니다.

또, 100%의 높이를 원하는지, 같은 높이를 원하는지에 따라서도 답이 다릅니다.보통 같은 높이입니다.높이가 100%라면 답은 약간 다릅니다.

이것은 디자이너들에게 항상 다뤄지는 짜증나는 문제입니다.문제는 CSS의 BODY와 HTML에서 높이를 100%로 설정해야 한다는 것입니다.

html,body {
    height:100%;
}

이 무의미해 보이는 코드는 브라우저에 100%의 의미를 정의하는 것입니다.짜증나긴 하지만 그게 가장 간단한 방법이야

두 개의 컬럼을 다음과 같이 설정합니다.display: table-cell;float: left;잘 동작합니다.

예기치 않게 짧은 콘텐츠 div가 발생할 경우 탐색 div를 잘라내도 괜찮다면 적어도 한 가지 쉬운 방법이 있습니다.

#main {
position: relative;
}

#main #navigation {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 10em; /* or whatever */
}

#main #content {
margin: 0;
margin-left: 10em; /* or whatever width you set for #navigation */
}

그렇지 않으면 가짜 기둥 기술이 있습니다.

#main {
    overflow: hidden;
}
#navigation, #content {
    margin-bottom: -1000px;
    padding-bottom: 1000px;
}

jQuery 사용:

$(function() {
    function unifyHeights() {
        var maxHeight = 0;
        $('#container').children('#navigation, #content').each(function() {
            var height = $(this).outerHeight();
            // alert(height);
            if ( height > maxHeight ) {
                maxHeight = height;
            }
        });
        $('#navigation, #content').css('height', maxHeight);
    }
    unifyHeights();
});
#main {
   display: table;
} 
#navigation, #content {
   display: table-cell;
}

예를 보세요.

맨 아래 여백을 100%로 만들어 보세요.

margin-bottom: 100%;

height : <percent>상위 레벨에서 픽셀, EMS 등의 고정 높이로 지정된 백분율의 모든 부모 노드가 있는 경우에만 작동합니다.이렇게 하면 높이가 요소까지 계단식으로 내려갑니다.

앞서 @Travis에서 설명한 바와 같이 html 및 body 요소를 100% 지정하여 노드까지 페이지 높이를 캐스케이드할 수 있습니다.

오랜 검색과 시도 끝에 문제 해결은 없었다.

style = "height:100%;"

칠드런 디브에

그리고 부모에게는 이것을 적용한다.

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

또, 부트스트랩을 사용하고 있기 때문에, 응답은 손상되지 않았습니다.

display: grid

2021 리더의 경우:

이것을 시험해 보세요.

.parent {
  position: relative;

  display: flex;                 // And you will probably need this too.
  flex-direction: row;           // or column.
}

.child {
  position: absolute;
  top: 0;
  bottom: 0;

  align-self: center;            // And you will probably need this too.
}

제가 하고 있는 일은 다음과 같습니다.

글에서 설명한 방법에 따라 작성했습니다.덜 역동적인 솔루션:

HTML:

<div id="container3">
    <div id="container2">
        <div id="container1">
            <div id="col1">Column 1</div>
            <div id="col2">Column 2</div>
            <div id="col3">Column 3</div>
        </div>
    </div>
</div>

감소:

/* Changes these variables to adjust your columns */
@col1Width: 60%;
@col2Width: 1%;
@padding: 0%;

/* Misc variable. Do not change */
@col3Width: 100% - @col1Width - @col2Width;

#container3 {
    float: left;
    width: 100%;
    overflow: hidden;
    background-color: red;
    position: relative;

    #container2 {
        float: left;
        width: 100%;
        position: relative;
        background-color: yellow;
        right: @col3Width;

        #container1 {
            float: left;
            width: 100%;
            position: relative;
            right: @col2Width;
            background-color: green;

            #col1 {
                float: left;
                width: @col1Width - @padding * 2;
                position: relative;
                left: 100% - @col1Width + @padding;
                overflow: hidden;
            }

            .col2 {
                float: left;
                width: @col2Width - @padding * 2;
                position: relative;
                left: 100% - @col1Width + @padding + @padding * 2;
                overflow: hidden;
            }

            #col3 {
                float: left;
                width: @col3Width - @padding * 2;
                position: relative;
                left: 100% - @col1Width + @padding + @padding * 4;
                overflow: hidden;
            }
        }
    }
}

질문이 나온지 한참이 지났다는 것을 알지만, 쉬운 해결책을 찾았고 누군가 그것을 사용할 수 있을 것 같았다(영어가 서툴러서 죄송합니다).여기 있습니다.

CSS

.main, .sidebar {
    float: none;
    padding: 20px;
    vertical-align: top;
}
.container {
    display: table;
}
.main {
    width: 400px;
    background-color: LightSlateGrey;
    display: table-cell;
}
.sidebar {
    width: 200px;
    display: table-cell;
    background-color: Tomato;
}

HTML

<div class="container clearfix">
    <div class="sidebar">
        simple text here
    </div>
    <div class="main">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam congue, tortor in mattis mattis, arcu erat pharetra orci, at vestibulum lorem ante a felis. Integer sit amet est ac elit vulputate lobortis. Vestibulum in ipsum nulla. Aenean erat elit, lacinia sit amet adipiscing quis, aliquet at erat. Vivamus massa sem, cursus vel semper non, dictum vitae mi. Donec sed bibendum ante.
    </div>
</div>

간단한 예.응답성으로 전환할 수 있습니다.

솔루션:

$(window).resize(function() {
   $('#div_to_occupy_the_rest').height(
        $(window).height() - $('#div_to_occupy_the_rest').offset().top
    );
});

CSS Flexbox 사용

.flex-container {
  display: flex;
  background-color: DodgerBlue;
}

.flex-container > div {
  background-color: #f1f1f1;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div class="flex-container">
  <div>1</div>
  <div>2</div>
  <div>3</div>  
</div>

<p>A Flexible Layout must have a parent element with the <em>display</em> property set to <em>flex</em>.</p>

<p>Direct child elements(s) of the flexible container automatically becomes flexible items.</p>

</body>
</html>

조금 늦을지도 모르지만, 조금 엉터리인 작품을 발견했어요.첫째, 부모에게 유연성과 100vh의 높이를 부여합니다.

다음과 같은 경우:

.parent {
   display: flex;
   justify-content: center;
   align-items: center;
   height: 100vh;/* Can be less depends on the container, basically this forces the element to expand */
}

ㅇㅇㅇㅇㄹㄹㄹㄹㄹㄹㄹㄹㄹㄹㄴㄴㄴㄴㄴㄴㄴㄴㄴㄴㄴㄴㄴㄴdisplay: flex로로 합니다.div#main,align-self: stretch로로 합니다.div#navigation.

<div id="header"></div>

<div id="main">
  <div id="navigation"></div>
  <div id="content"></div>
</div>

<div id="footer"></div>

// CSS file
#main {
  display: flex;
}

#navigation {
  align-self: stretch;
}    

문제의 제목과 내용에 약간의 모순이 있다.제목은 부모 디바이를 나타내지만, 질문은 마치 두 형제 디바(내비게이션과 내용)의 높이가 같기를 바라는 것처럼 들린다.

(a) 네비게이션과 콘텐츠의 높이를 메인 높이의 100%로 할 것인가, 아니면 (b) 네비게이션과 콘텐츠의 높이를 동일하게 할 것인가?

(b)...그렇다면 현재의 페이지 구조(적어도 순수한 CSS와 스크립팅이 없는 상태에서는)로는 할 수 없다고 생각합니다.다음과 같은 작업이 필요할 수 있습니다.

<main div>
    <content div>
         <navigation div></div>
    </div>
</div>

콘텐츠 div를 네비게이션 영역의 폭에 관계없이 왼쪽 여백으로 설정합니다.이렇게 하면 콘텐츠의 내용이 네비게이션 오른쪽에 있고, 네비게이션 칸을 콘텐츠 높이의 100%로 설정할 수 있습니다.

편집: 완전히 머릿속으로 하고 있습니다만, 내비게이션의 왼쪽 여백을 음의 값으로 설정하거나 왼쪽 여백을 0으로 설정하여 맨 왼쪽으로 되돌릴 필요가 있습니다.문제는, 이것을 실현하는 방법은 여러 가지가 있지만, 모든 브라우저와 호환성이 있는 것은 아닙니다.

[또 다른 답변에서 디미티의 'Less 코드' 참조]이게 무슨 '의사 코드'인가?

내가 아는 바로는 효과가 있을 만한 가짜 기둥 기술을 사용해 보세요.

http://www.alistapart.com/articles/fauxcolumns/

이것이 도움이 되기를 바랍니다:)

부여position: absolute;내 경우에서 일하는 아이에게

이 답변은 CSS에 구현되어 있는 CSS 플렉스박스 및 그리드가 이상적이지 않습니다.다만, 아직 유효한 솔루션입니다.

작은 화면에서는 col1, col2, col3가 서로 겹쳐져 있기 때문에 높이를 자동으로 유지하는 것이 좋습니다.

그러나 미디어 쿼리 중단점 후에는 모든 열에 대해 동일한 높이로 콜을 서로 옆에 표시해야 합니다.

1125px는 모든 열을 동일한 높이로 설정하려는 창 너비 중단점의 예에 불과합니다.

<div class="wraper">
    <div class="col1">Lorem ipsum dolor sit amet.</div>
    <div class="col2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eos laudantium, possimus sed, debitis amet in, explicabo dolor similique eligendi officia numquam eaque quae illo magnam distinctio odio, esse vero aspernatur.</div>
    <div class="col3">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem, odio qui praesentium.</div>
</div>

물론 필요하다면 중단점을 더 설정할 수도 있습니다.

<script>
    $(document).ready(function(){
        $(window).on('load resize', function() {
            let vraperH = $('.wraper').height();
            if (window.innerWidth>= 1125) {
              $('.col1').height(vraperH);
              $('.col2').height(vraperH);
              $('.col3').height(vraperH);
            }
            if (window.innerWidth < 1125) {
              $('.col1').height('auto');
              $('.col2').height('auto');
              $('.col3').height('auto');
            }
        });
    });
</script>

저도 같은 문제가 있었습니다. Hakam Forstok의 답변에 따라 작동했습니다. 저는 작은 예를 만들었습니다. 경우에 따라서는 추가하지 않고도 작동될 수 있습니다.display: flex;그리고.flex-direction: column;모컨테이너에

.row {
    margin-top: 20px;
}

.col {
    box-sizing: border-box;
    border: solid 1px #6c757d;
    padding: 10px;
}

.card {
    background-color: #a0a0a0;
    height: 100%;
}

JSFiddle

앞에서 설명한 바와 같이 Flexbox가 가장 쉽습니다.예:

#main{ display: flex; align-items:center;}

그러면 모든 자식 요소가 부모 요소 내의 중심에 정렬됩니다.

.row-eq-height {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display:         flex;
 }

송신원:

http://getbootstrap.com.vn/examples/equal-height-columns/equal-height-columns.css

부트스트랩을 사용하지만 부트스트랩을 사용할 필요는 없습니다.이 오래된 질문에 대답하는 것은 저에게 효과가 있었고, 구현하기 매우 쉬울 것 같습니다.

질문에 대한 답변과 동일했습니다.

이 방법은 효과가 있습니다.HTML 섹션에 clear 스타일을 가진 최종 요소 추가: both;

    <div style="clear:both;"></div>

그 이전의 모든 것이 높이에 포함됩니다.

나에게 효과가 있었던 건style={{ display: 'flex', overflowY: "auto" }}아이의 모든 부모에게 그리고 나서style={{ overflowY: "auto" }}아이 자신에게도요.

다음 코드는 최소 높이를 설정할 수 있는 기능을 제공합니다.scroll div플렉스만 사용해도 부모 키 100%로 만들 수 있습니다.

CSS:

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

.scroll {
  overflow: auto;
  flex: 1 0 50px;
}

HTML:

<div class="main">
  <div class="scroll">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </div>
</div>

이 코드는 나에게 완벽하게 작동한다.

<html>
    <body style="display: flex;">
        <div style="position: absolute; width: 100%; height: 100%; background-color: aliceblue">
            <table style="width: 100%; height: 100%;">
               <tr>
                   <td style="width: 70%; background-color: green"></td>
                   <td style="background-color: red"></td>
               </tr>
            </table>
       </div>
   </body>

언급URL : https://stackoverflow.com/questions/1122381/how-to-force-child-div-to-be-100-of-parent-divs-height-without-specifying-pare

반응형