문제

나는 각각이 가변 너비를 가질 수있는 2 열 div 레이아웃을 원한다.

div {
    float: left;
}
.second {
    background: #ccc;
}
<div>Tree</div>
<div class="second">View</div>

'Tree'Div가 필요한 공간을 채운 후 'View'Div가 사용 가능한 전체 너비로 확장되기를 원합니다. 현재 내 'View'Div는 컨텐츠로 크기가 커져서 두 DIV가 전체 높이를 차지하면 양호합니다.

중복 면책 조항이 아닙니다 :

플로트 : 왼쪽이 설정되면 DIV를 최대 너비로 확장합니다.왼쪽에는 고정 너비가 있기 때문입니다.

Div에 대한 도움 - DIV를 남은 너비에 맞추십시오.두 열이 필요하기 때문에 둘 다 왼쪽에 정렬되었습니다

도움이 되었습니까?

해결책

이것에 대한 해결책은 실제로 매우 쉽지만 모두 분명한. 특정 방식으로 플로트와 상호 작용하는 "블록 포맷 컨텍스트"(BFC)라는 것을 트리거해야합니다.

그냥 두 번째 div를 가져 가서 플로트를 제거하고 줘 overflow:hidden 대신에. 가시적 이외의 오버플로 값은 설정된 블록이 BFC가됩니다. BFC는 자손 수레가 그들을 탈출하도록 허용하지 않으며, 형제/조상 수레가 그들을 침입하도록 허용하지 않습니다. 여기서 순 효과는 플로팅 된 div가 그 일을한다는 것입니다. 그러면 두 번째 div는 일반적인 블록이 될 것이며, 사용 가능한 모든 너비를 차지합니다. 플로트가 차지하는 것을 제외하고.

IE6과 7에서 HASLAYOUT을 트리거해야 할 수도 있지만 모든 현재 브라우저에서 작동해야합니다.

시민:

다른 팁

방금 플렉스 박스의 마법을 발견했습니다 (Display : Flex). 이 시도:

<style>
  #box {
    display: flex;
  }
  #b {
    flex-grow: 100;
    border: 1px solid green;
  }
</style>
<div id='box'>
 <div id='a'>Tree</div>
 <div id='b'>View</div>
</div>

플렉스 박스는 CSS가 15 년 동안 원했던 제어를 제공합니다. 마침내 여기! 더 많은 정보: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

이것은 CSS와 관련하여 테이블과 어렵고 (적어도 브라우저 크로스 의미에서는 불가능하지는 않지만) 어려운 일의 좋은 예일 것입니다.

두 열이 고정 너비라면 쉽습니다.

열 중 하나가 고정 너비 인 경우 약간 어렵지만 완전히 가능합니다.

두 열 변수 너비를 사용하면 IMHO 2 열 테이블 만 사용하면됩니다.

이 솔루션을 확인하십시오

.container {
  width: 100%;
  height: 200px;
  background-color: green;
}
.sidebar {
  float: left;
  width: 200px;
  height: 200px;
  background-color: yellow;
}
.content {
  background-color: red;
  height: 200px;
  width: auto;
  margin-left: 200px;
}
.item {
  width: 25%;
  background-color: blue;
  float: left;
  color: white;
}
.clearfix {
  clear: both;
}
<div class="container">
  <div class="clearfix"></div>
  <div class="sidebar">width: 200px</div>

  <div class="content">
    <div class="item">25%</div>
    <div class="item">25%</div>
    <div class="item">25%</div>
    <div class="item">25%</div>
  </div>
</div>

여기서 도움이 될 수 있습니다 ...

<html>

<head>
  <style type="text/css">
    div.box {
      background: #EEE;
      height: 100px;
      width: 500px;
    }
    div.left {
      background: #999;
      float: left;
      height: 100%;
      width: auto;
    }
    div.right {
      background: #666;
      height: 100%;
    }
    div.clear {
      clear: both;
      height: 1px;
      overflow: hidden;
      font-size: 0pt;
      margin-top: -1px;
    }
  </style>
</head>

<body>
  <div class="box">
    <div class="left">Tree</div>
    <div class="right">View</div>
    <div class="clear" />
  </div>
</body>

</html>

Flexbox 솔루션

이것이 바로 flex-grow 속성은 용입니다.

html, body {
  height: 100%;
}
.wrapper {
  display: flex;
  height: 100%;
}
.second {
  flex-grow: 1;
}
<div class="wrapper">
  <div style="background: #bef;">Tree</div>
  <div class="second" style="background: #faa;">View</div>
</div>

메모: 필요한 경우 Flex 벤더 접두사를 추가하십시오 지원되는 브라우저.

사용 calc:

.leftSide {
  float: left;
  width: 50px;
  background-color: green;
}
.rightSide {
  float: left;
  width: calc(100% - 50px);
  background-color: red;
}
<div style="width:200px">
  <div class="leftSide">a</div>
  <div class="rightSide">b</div>
</div>

이것의 문제는 모든 너비가 값 (PX 및 EM은 잘 작동) 또는 명시 적으로 정의 된 것의 백분율로 명시 적으로 정의되어야한다는 것입니다.

사람들이 왜 오래된 원주민 레이아웃을위한 순수한 CSS 솔루션을 찾기 위해 열심히 노력하는지 이해하지 못합니다. TABLE 꼬리표.

모든 브라우저에는 여전히 테이블 레이아웃 로직이 있습니다 ... 아마도 공룡이라고 부르지 만 도움을 드리겠습니다.

<table WIDTH=100% border=0 cellspacing=0 cellpadding=2>
  <tr>
    <td WIDTH="1" NOWRAP bgcolor="#E0E0E0">Tree</td>
    <td bgcolor="#F0F0F0">View</td>
  </tr>
</table>

크로스 브라우저 호환성 측면에서 훨씬 덜 위험합니다.

<html>

<head>
  <style type="text/css">
    div.box {
      background: #EEE;
      height: 100px;
      width: 500px;
    }
    div.left {
      background: #999;
      float: left;
      height: 100%;
      width: auto;
    }
    div.right {
      background: #666;
      height: 100%;
    }
    div.clear {
      clear: both;
      height: 1px;
      overflow: hidden;
      font-size: 0pt;
      margin-top: -1px;
    }
  </style>
</head>

<body>
  <div class="box">
    <div class="left">Tree</div>
    <div class="right">View</div>
    <div class="right">View</div>
    <div style="width: <=100% getTreeWidth()100 %>">Tree</div>
    <div class="clear" />
  </div>
  <div class="ColumnWrapper">
    <div class="Colum­nOne­Half">Tree</div>
    <div class="Colum­nOne­Half">View</div>
  </div>

</body>

</html>

당신은 시도 할 수 있습니다 CSS 그리드 레이아웃.

dl {
  display: grid;
  grid-template-columns: max-content auto;
}

dt {
  grid-column: 1;
}

dd {
  grid-column: 2;
  margin: 0;
  background-color: #ccc;
}
<dl>
  <dt>lorem ipsum</dt>
  <dd>dolor sit amet</dd>
  <dt>carpe</dt>
  <dd>diem</dd>
</dl>

simpl.css의 플러그에 감사드립니다!

모든 열을 감싸는 것을 잊지 마십시오 ColumnWrapper 그렇게 좋아요.

<div class="ColumnWrapper">
    <div class="Colum­nOne­Half">Tree</div>
    <div class="Colum­nOne­Half">View</div>
</div>

나는 simpl.css의 버전 1.0을 출시하려고합니다.

약간 다른 구현,

두 개의 div 패널 (콘텐츠+추가), 나란히, content panel IF를 확장합니다 extra panel 존재하지 않습니다.

jsfiddle : http://jsfiddle.net/qltmf/1722/

팻 - 당신이 옳다. 그렇기 때문에이 솔루션은 "공룡"과 동시대 사람들을 모두 만족시킬 것입니다. :)

.btnCont {
  display: table-layout;
  width: 500px;
}

.txtCont {
  display: table-cell;
  width: 70%;
  max-width: 80%;
  min-width: 20%;
}

.subCont {
  display: table-cell;
  width: 30%;
  max-width: 80%;
  min-width: 20%;
}
<div class="btnCont">
  <div class="txtCont">
    Long text that will auto adjust as it grows. The best part is that the width of the container would not go beyond 500px!
  </div>
  <div class="subCont">
    This column as well as the entire container works like a table. Isn't Amazing!!!
  </div>
</div>

다른 열의 너비가 고정 된 경우 calc CSS 기능 모든 일반적인 브라우저에서 작업합니다:

width: calc(100% - 20px) /* 20px being the first column's width */

이런 식으로 두 번째 행의 너비는 계산되고 (즉, 나머지 너비) 반응 적으로 적용됩니다.

Flex -Grow- 이것은 필요한 경우 플렉스 아이템이 성장하는 능력을 정의합니다. 비율 역할을하는 단위가없는 값을 받아들입니다. 플렉스 컨테이너 내부의 사용 가능한 공간의 양을 지시합니다.

모든 품목에 Flex-Grow가 1으로 설정되어 있으면 컨테이너의 나머지 공간은 모든 어린이에게 똑같이 배포됩니다. 어린이 중 하나의 값이 2 인 경우 나머지 공간은 다른 공간보다 두 배나 많은 공간을 차지합니다 (또는 적어도 시도 할 것입니다). 더보기 여기

.parent {
  display: flex;
}

.child {
  flex-grow: 1; // It accepts a unitless value that serves as a proportion
}

.left {
  background: red;
}

.right {
  background: green;
}
<div class="parent"> 
  <div class="child left">
      Left 50%
  </div>
   <div class="child right">
      Right 50%
  </div>
</div>

이것이 당신이 기대하는 대답인지 확실하지 않지만 나무의 너비를 '자동'과 '보기'의 너비를 100%로 설정하지 않겠습니까?

사용 가능한 CSS 레이아웃 프레임 워크를 살펴보십시오. 추천합니다 단순합니다 또는 약간 더 복잡한 청사진 프레임 워크.

Simpl (하나만 가져 오는 것과 관련이있는 경우 simpl.css 파일), 당신은 이것을 할 수 있습니다 :

<div class="Colum­nOne­Half">Tree</div>
<div class="Colum­nOne­Half">View</div>

, 50-50 레이아웃의 경우 :

<div class="Colum­nOne­Quarter">Tree</div>
<div class="Colum­nThreeQuarters">View</div>

, 25-75의 경우.

그렇게 간단합니다.

jQuery $ (document) .ready ()에서 호출하는 JavaScript 함수를 작성했습니다. 이것은 부모 div의 모든 자녀를 구문 분석하고 가장 올바른 자녀 만 업데이트 할 것입니다.

HTML

...
<div class="stretch">
<div style="padding-left: 5px; padding-right: 5px; display: inline-block;">Some text
</div>
<div class="underline" style="display: inline-block;">Some other text
</div>
</div>
....

자바 스크립트

$(document).ready(function(){
    stretchDivs();
});

function stretchDivs() {
    // loop thru each <div> that has class='stretch'
    $("div.stretch").each(function(){
        // get the inner width of this <div> that has class='stretch'
        var totalW = parseInt($(this).css("width"));
        // loop thru each child node
        $(this).children().each(function(){
            // subtract the margins, borders and padding
            totalW -= (parseInt($(this).css("margin-left")) 
                     + parseInt($(this).css("border-left-width")) 
                     + parseInt($(this).css("padding-left"))
                     + parseInt($(this).css("margin-right")) 
                     + parseInt($(this).css("border-right-width")) 
                     + parseInt($(this).css("padding-right")));
            // if this is the last child, we can set its width
            if ($(this).is(":last-child")) {
                $(this).css("width","" + (totalW - 1 /* fudge factor */) + "px");
            } else {
                // this is not the last child, so subtract its width too
                totalW -= parseInt($(this).css("width"));
            }
        });
    });
}

호출 클래스가 포함 된 W3의 CSS 라이브러리를 사용할 수 있습니다. rest 그것은 바로 다음과 같습니다.

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<div class="w3-row">
  <div class="w3-col " style="width:150px">
    <p>150px</p>
  </div>
  <div class="w3-rest w3-green">
    <p>w3-rest</p>
  </div>
</div>

페이지에서 CSS 라이브러리를 연결하는 것을 잊지 마십시오. header:

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

공식 데모는 다음과 같습니다. W3 School Tryit 편집자

Flexbox를 사용하는 것은 매우 쉽습니다. 아래 스 니펫을 참조하십시오. 흐름을 제어하고 전역 높이를 설정하기 위해 래퍼 컨테이너를 추가했습니다. 요소를 식별하기 위해 국경이 추가되었습니다. DIV는 이제 필요에 따라 전체 높이로 확장됩니다. 공급 업체 접두사는 아직 완전히 지원되지 않았으므로 실제 시나리오에서 Flexbox에 사용해야합니다.

Flexbox를 사용하여 레이아웃을 이해하고 설계 할 수있는 무료 도구를 개발했습니다. 여기에서 확인하십시오.http://algid.com/flex-designer

.container{
    height:180px;
    border:3px solid #00f;
    display:flex;
    align-items:stretch;
}
div {
    display:flex;
    border:3px solid #0f0;
}
.second {
    display:flex;
    flex-grow:1;
    border:3px solid #f00;
}
<div class="container">
    <div>Tree</div>
    <div class="second">View</div>
</div>

두 너비가 가변 길이 인 경우 스크립팅 또는 서버 측면에서 너비를 계산하지 않겠습니까?

<div style="width: <=% getTreeWidth() %>">Tree</div>

<div style="width: <=% getViewWidth() %>">View</div>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top