Rozwiń div, aby wypełnić pozostałą szerokość

Chcę mieć dwukolumnowy układ div, gdzie każdy może mieć zmienną szerokość np.

div {
  float: left;
}

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

Chcę, aby div' view ' rozszerzył się na całą szerokość dostępną po wypełnieniu wymaganego miejsca przez div 'tree'.

Obecnie Mój' widok ' div jest zmieniany na zawartość, którą zawiera Będzie to również dobre, jeśli oba div zajmują całą wysokość.


Not duplicate disclaimer:

Author: Penny Liu, 2009-08-11

21 answers

Rozwiązanie tego problemu jest w rzeczywistości bardzo proste, ale nie w wszystkich oczywistych. Musisz uruchomić coś, co nazywa się "kontekstem formatowania bloków" (BFC), który oddziałuje z pływakami w określony sposób.

Po prostu weź drugi div, Usuń float i daj go overflow:hidden. Każda wartość przepełnienia inna niż widoczna sprawia, że blok, na którym jest ustawiony, staje się BFC. BFC nie pozwalają pływakom Potomków na ucieczkę od nich, ani nie pozwalają pływakom rodzeństwa / przodków na wtargnięcie do nich. Sieć efekt jest taki, że pływający div zrobi swoje, wtedy drugi div będzie zwykłym blokiem, zajmującym całą dostępną szerokość z wyjątkiem tego zajmowanego przez float .

Powinno to działać we wszystkich obecnych przeglądarkach, chociaż może być konieczne uruchomienie hasLayout w IE6 i 7. Nie pamiętam.

Dema:

 1041
Author: Xanthir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-02-08 21:32:33

Właśnie odkryłem magię flex boxów (display: flex). Spróbuj tego:

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

Flex Boxy dają mi kontrolę, której pragnąłem css od 15 lat. W końcu tu jest! Więcej informacji: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

 130
Author: B T,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-13 22:43:43

Użyj CSS Flexbox flex-grow własności, aby to osiągnąć.

html, body {
  height: 100%;
}
body {
  display: flex;
}
.second {
  flex-grow: 1;
}
<div style="background: #bef;">Tree</div>
<div class="second" style="background: #ff9;">View</div>
 42
Author: Reggie Pinkham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-09-13 01:37:35

Byłby to dobry przykład czegoś, co jest trywialne z tabelami i trudne (jeśli nie niemożliwe, przynajmniej w sensie między przeglądarkowym) do czynienia z CSS.

Gdyby obie kolumny miały stałą szerokość, byłoby to łatwe.

Gdyby jedna z kolumn miała stałą szerokość, byłoby to nieco trudniejsze, ale całkowicie wykonalne.

Przy zmiennej szerokości obu kolumn IMHO wystarczy użyć tabeli dwukolumnowej.

 27
Author: cletus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-11 12:49:59

Sprawdź To rozwiązanie

.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>
 22
Author: angel.dimitrov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-25 22:51:57

Użycie 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>

Problem polega na tym, że wszystkie szerokości muszą być jawnie zdefiniowane, albo jako wartość (px I em działają dobrze), albo jako procent czegoś jawnie zdefiniowanego.

 19
Author: joel Moses,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-22 15:59:13

To może pomóc...

<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>
 15
Author: a6hi5h3k,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-25 22:50:30

Jeśli szerokość drugiej kolumny jest stała, co powiesz na użycie calc funkcja CSS działająca dla wszystkich popularnych przeglądarek :

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

W ten sposób zostanie obliczona szerokość drugiego wiersza (tzn. pozostała szerokość) i zastosowana responsywnie.

 7
Author: anit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-02 10:13:20

Nie rozumiem, dlaczego ludzie są gotowi tak ciężko pracować, aby znaleźć czyste CSS rozwiązanie dla prostych układów kolumnowych, które są tak łatwe przy użyciu starego tagu TABLE.

Wszystkie przeglądarki nadal mają logikę układu tabeli... Nazwij mnie może dinozaurem, ale niech ci pomoże.

<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>
Znacznie mniej ryzykowne, jeśli chodzi o kompatybilność między przeglądarkami.
 5
Author: PatM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-25 23:12:06

<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>
 3
Author: A.Pramod Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-29 21:43:35

Możesz spróbować CSS Grid Layout .

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>
 3
Author: canon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-25 16:34:46

Flex-grow-określa zdolność do wzrostu elementu flex w razie potrzeby. Przyjmuje wartość bez jednostek, która służy jako proporcja. Określa, jaką ilość dostępnego miejsca wewnątrz pojemnika flex powinien zająć przedmiot.

Jeśli wszystkie elementy mają wartość flex-grow ustawioną na 1, pozostała przestrzeń w kontenerze zostanie rozdzielona równo na wszystkie dzieci. Jeśli jedno z dzieci ma wartość 2, pozostała przestrzeń zajmie dwa razy więcej miejsca niż pozostałe (lub spróbuje, przynajmniej). Zobacz więcej tutaj

.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>
 2
Author: Stanislav Ostapenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-11-08 14:23:14

Nieco inna implementacja,

Dwa panele div (content+extra), obok siebie, content panel rozszerza się, jeśli extra panel nie jest obecny.

Jsfiddle: http://jsfiddle.net/qLTMf/1722/

 1
Author: Nagendra Rao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-06 12:04:50

Pat-masz rację. Dlatego takie rozwiązanie zadowoliłoby zarówno "dinozaury", jak i współczesnych. :)

.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>
 1
Author: johnmanoahs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-02 09:53:20

Możesz użyć biblioteki CSS W3, która zawiera klasę o nazwie rest właśnie tak:

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

Nie zapomnij połączyć biblioteki CSS w header strony:

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

Oto oficjalne demo: W3 School Tryit Editor

 1
Author: Manar Gul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-02 09:59:47

Nie jestem pewien, czy jest to odpowiedź, której oczekujesz, ale dlaczego nie ustawisz szerokości drzewa na "auto", a szerokość "Widok" na 100%?

 0
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-11 12:49:25

Spójrz na dostępne frameworki układu CSS. Polecam Simpl lub, nieco bardziej złożony, plan ramowy.

Jeśli używasz Simpl (który polega na importowaniu tylko jednego simpl.plik css ), możesz to zrobić:

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

, dla układu 50-50 lub:

<div class="Colum­nOne­Quarter">Tree</div>
<div class="Colum­nThreeQuarters">View</div>
25-75. To takie proste.
 0
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-11 14:17:08

Dzięki za wtyczkę Simpl.css!

Pamiętaj, aby zawinąć wszystkie kolumny w ColumnWrapper w ten sposób.

<div class="ColumnWrapper">
    <div class="Colum­nOne­Half">Tree</div>
    <div class="Colum­nOne­Half">View</div>
</div>
Mam zamiar wydać wersję 1.0 Simpl.css tak pomóc szerzyć słowo!
 0
Author: Shaggy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-04 09:59:39

Napisałem funkcję javascript, którą wywołuję z jQuery $(document).ready (). To przetworzy wszystkie dzieci rodzica div I zaktualizuje tylko właściwe najbardziej dziecko.

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>
....

Javascript

$(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"));
            }
        });
    });
}
 0
Author: bcr666,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-11 05:19:13

Jest to dość łatwe przy użyciu flexbox. Zobacz poniższy fragment. Dodałem pojemnik do owijania, aby kontrolować przepływ i ustawić globalną wysokość. Dodano również granice w celu identyfikacji elementów. Zauważ, że div teraz rozszerzyć do pełnej wysokości, jak również, w razie potrzeby. Prefiksy dostawcy powinny być używane dla flexbox w scenariuszu rzeczywistym, ponieważ nie jest jeszcze w pełni obsługiwany.

Opracowałem darmowe narzędzie do rozumienia i projektowania układów za pomocą flexbox. Zobacz też proszę.: 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>
 0
Author: Mario Vázquez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-12 08:06:45

Jeśli obie szerokości są zmienną długością, dlaczego nie obliczysz szerokości za pomocą jakiegoś skryptu lub strony serwera?

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

<div style="width: <=% getViewWidth() %>">View</div>
 -5
Author: amischiefr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-11 12:52:59