代码之家  ›  专栏  ›  技术社区  ›  wyc

如何使一个DIV填充剩余的水平空间?

  •  374
  • wyc  · 技术社区  · 15 年前

    我有两张沙发床:一张在左边,一张在右边。左边的那个宽度是固定的,我希望右边的那个填充剩余的空间。

        #search {
            width: 160px;
            height: 25px;
            float: left;
            background-color: #ffffff;
        }
        #navigation {
            width: 780px;
            float: left;  
            background-color: #A53030;
        }
    <div id="search">Text</div>
    <div id="navigation">Navigation</div>
    25 回复  |  直到 5 年前
        1
  •  59
  •   Munawir    7 年前

    这似乎完成了你的目标。

    #left {
      float:left;
      width:180px;
      background-color:#ff0000;
    }
    #right {
      width: 100%;
      background-color:#00FF00;
    }
    <div>
      <div id="left">
        left
      </div>
      <div id="right">
        right
      </div>
    </div>
        2
  •  247
  •   KyleMit Steven Vachon    6 年前

    我从布什利的答案中发现的问题是,如果右栏比左栏长,它将围绕左栏,继续填充整个空间。这不是我想要的行为。在搜索了很多“解决方案”后,我发现了这个 awesome tutorial 关于创建三列页面。

    作者提出了三种不同的方法,一种是固定宽度,一种是三列可变,另一种是固定外柱可变宽度和中间可变宽度。比我发现的其他例子更优雅和有效。大大提高了我对CSS布局的理解。

    基本上,在上面的简单例子中,将第一列向左浮动,并给它一个固定的宽度。然后给右边的列一个比第一列宽一点的左边距。就这样。完成。Ala Boushley代码:

    这里有一个演示 堆栈片段 和; jsFiddle

    #left {
      float: left;
      width: 180px;
    }
    
    #right {
      margin-left: 180px;
    }
    
    /* just to highlight divs for example*/
    #left { background-color: pink; }
    #right { background-color: lightgreen;}
    <div id="left">  left  </div>
    <div id="right"> right </div>

    在Boushley的例子中,左列将另一列保持在右边。一旦左列结束,右列就开始重新填充整个空间。在这里,右栏只是与页面进一步对齐,左栏占据了它的大的胖边。不需要流交互。

        3
  •  122
  •   Chin    7 年前

    解决方案来自显示属性。

    基本上,您需要使两个div像表格单元格一样工作。所以不用 float:left ,你必须使用 display:table-cell 在两个div上,对于动态宽度div,需要设置 width:auto; 也。两个分隔符应放置在一个100%宽的容器中, display:table 财产。

    这是CSS:

    .container {display:table;width:100%}
    #search {
      width: 160px;
      height: 25px;
      display:table-cell;
      background-color: #FFF;
    }
    #navigation {
      width: auto;
      display:table-cell;
      /*background-color: url('../images/transparent.png') ;*/
      background-color: #A53030;
    }
    
    *html #navigation {float:left;}
    

    和HTML:

    <div class="container">
       <div id="search"></div>
       <div id="navigation"></div>
    </div>
    

    重要提示:对于Internet Explorer,需要在“动态宽度”DIV上指定float属性,否则空间将不会被填充。

    我希望这能解决你的问题。 如果你愿意的话,你可以阅读我写的关于这个的完整文章 my blog .

        4
  •  98
  •   zrooda    10 年前

    由于这是一个相当流行的问题,我倾向于使用bfc共享一个很好的解决方案。
    以下代码笔示例 here .

    .left {
      float: left;
      width: 100px;
    }
    .right {
      overflow: auto;
    }
    

    在这种情况下, overflow: auto 触发上下文行为并使正确的元素展开 只有 到可用的剩余宽度,如果 .left 消失。对于许多UI布局来说,这是一个非常有用和干净的技巧,但起初可能很难理解“为什么它能工作”。

        5
  •  85
  •   TylerH Ash Burlaczenko    7 年前

    现在,你应该使用 flexbox 方法(可能适用于具有浏览器前缀的所有浏览器)。

    .container {
        display: flex;
    }
    
    .left {
        width: 180px;
    }
    
    .right {
        flex-grow: 1;
    }
    

    更多信息: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

        6
  •  20
  •   Marcos B.    9 年前

    如果您不需要与某些浏览器的旧版本兼容(即 例如8或更少)您可以使用 calc() CSS功能:

    #left {
       float:left;
       width:180px;
       background-color:#ff0000;
    }
    
    #right {
       float: left;
       width: calc(100% - 180px);
       background-color:#00FF00;
    }
    
        7
  •  15
  •   TylerH Ash Burlaczenko    7 年前

    @布什利的回答是最接近的,但有一个问题没有得到解决,已经指出。这个 正确的 DIV采用浏览器的整个宽度;内容采用预期的宽度。要更好地看到这个问题:

    <html>
    <head>
        <style type="text/css">
        * { margin: 0; padding: 0; }
        body {
            height: 100%;
        }
        #left {
            opacity: 0;
            height: inherit;
            float: left;
            width: 180px;
            background: green;
        }
        #right {
            height: inherit;
            background: orange;
        }
        table {
                width: 100%;
                background: red;
        }
        </style>
    </head>
    <body>
        <div id="left">
            <p>Left</p>
        </div>
        <div id="right">
            <table><tr><td>Hello, World!</td></tr></table>
        </div>
    </body>
    </html>
    

    http://jsfiddle.net/79hpS/

    内容在正确的位置(在火狐中),但是宽度不正确。当子元素开始继承宽度(例如表 width: 100% )它们的宽度等于浏览器的宽度,导致它们从页面右侧溢出,并创建一个水平滚动条(在Firefox中)或不浮动并向下推(在Chrome中)。

    你可以 修复这个 通过添加 overflow: hidden 在右栏。这将为内容和分区提供正确的宽度。此外,表将收到正确的宽度并填充剩余的可用宽度。

    我尝试了上面的其他一些解决方案,它们没有完全适用于某些边缘案例,只是过于复杂,无法保证修复它们。这是可行的,而且很简单。

    如果有任何问题或顾虑,请随时提出。

        8
  •  12
  •   Dariusz Sikorski    8 年前

    这里有一个接受的解决方案的小补丁,它可以防止右列落在左列下面。替换 width: 100%; 具有 overflow: hidden; 一个棘手的解决办法,如果有人不知道的话。

    <html>
    
    <head>
        <title>This is My Page's Title</title>
        <style type="text/css">
            #left {
                float: left;
                width: 180px;
                background-color: #ff0000;
            }
            #right {
                overflow: hidden;
                background-color: #00FF00;
            }
        </style>
    </head>
    
    <body>
        <div>
            <div id="left">
                left
            </div>
            <div id="right">
    
    
    right
        </div>
    </div>
    

    http://jsfiddle.net/MHeqG/2600/

    [编辑]同时检查三列布局的示例: http://jsfiddle.net/MHeqG/3148/

        9
  •  3
  •   chinchi11a    13 年前

    布什利的答案似乎是最好的方式,以便安排使用浮动。然而,它并非没有问题。扩展元素中的嵌套浮动将不可用;它将中断页面。

    当涉及到扩展元素时,所显示的方法基本上是“伪造它”——它实际上不是浮动的,它只是在使用它的边距来处理固定宽度的浮动元素。

    问题就在于:膨胀元件没有浮动。如果您尝试在扩展元素中嵌套浮动,那么这些“嵌套”浮动项实际上根本就不是嵌套的;当您尝试粘贴 clear: both; 在“嵌套的”浮动项下,最终也将清除顶级浮动。

    然后,为了使用Boushley的解决方案,我想补充一点,您应该放置一个DIV,如下所示: 浮萍 { 身高:100%; 宽度:100%; 浮动:左; } 把它直接放在展开的DIV中;所有展开的DIV的内容都应该放在fakefloat元素中。

    因此,我建议在这个特定的案例中使用表。浮动元素的设计并不是为了实现您想要的扩展,而使用表的解决方案则很简单。通常会有这样一个参数:浮动更适合布局,而不是表格。但无论如何,你并没有在这里使用浮动,你只是在装而已——在我看来,这种做法破坏了这个具体案例的文体论证的目的。

        10
  •  3
  •   nanobar    12 年前

    我尝试了上面关于液体左边的解决方案,固定右边的解决方案,但没有成功(我知道问题是相反的,但我认为这是相关的)。以下是工作原理:

    .wrapper {margin-right:150px;}
    .wrapper .left {float:left; width:100%; margin-right:-150px;}
    
    .right {float:right; width:150px;}
    
    <div class="wrapper"><div class="left"></div></div>
    <div class="right"></div>
    
        11
  •  3
  •   Community kfsone    7 年前

    我也遇到了类似的问题,我在这里找到了解决方案: https://stackoverflow.com/a/16909141/3934886

    解决方案是固定中心的DIV和液体侧柱。

    .center{
        background:#ddd;
        width: 500px;
        float:left;
    }
    
    .left{
        background:#999;
        width: calc(50% - 250px);
        float:left;
    }
    
    .right{
        background:#999;
        width: calc(50% - 250px);
        float:right;
    }
    

    如果您想要一个固定的左列,只需相应地更改公式。

        12
  •  3
  •   Post Impatica    8 年前

    如果要在两个项目之间的flexbox中填充剩余空间,请将以下类添加到要分隔的两个项目之间的空分区中:

    .fill {
      // This fills the remaining space, by using flexbox. 
      flex: 1 1 auto;
    }
    
        13
  •  3
  •   Ildar Zaripov    8 年前

    使用 display:flex

    <div style="width:500px; display:flex">
       <div style="width:150px; height:30px; background:red">fixed width</div>
    
       <div style="width:100%; height:30px; background:green">remaining</div>
    </div>
    
        14
  •  0
  •   user1700099    11 年前

    /* *CSS */

    #search {
     position: absolute;
     width: 100px;
    }
    .right-wrapper {
      display: table;
      width: 100%;
      padding-left:100px;
    }
    .right-wrapper #navigation {
     display: table-cell;
     background-color: #A53030;
    }
    

    /* *HTML */

    <div id="search"></div>
    <div class="right-wrapper">
       <div id="navigation"></div>
    </div>
    
        15
  •  0
  •   Julian Paolo Dayag    9 年前

    我有一个非常简单的解决方案! //html

    <div>
    <div id="left">
        left
    </div>
    <div id="right">
        right
    </div>
    

    /CSS

    #left {
    float:left;
    width:50%;
    position:relative;
    background-color:red;
    }
    #right {
    position:relative;
    background-color:#00FF00;}
    

    链接: http://jsfiddle.net/MHeqG/

        16
  •  0
  •   Tidan    9 年前

    我也遇到过类似的问题,并提出了以下几点,效果很好

    CSS:

    .top {
    width: auto;
    height: 100px;
    background-color: black;
    border: solid 2px purple;
    overflow: hidden;
    }
    .left {
    float:left;
    width:100px;
    background-color:#ff0000;
    padding: 10px;
    border: solid 2px black;
    }
    .right {
    width: auto;
    background-color:#00FF00;
    padding: 10px;
    border: solid 2px orange;
    overflow: hidden;
    }
    .content {
    margin: auto;
    width: 300px;
    min-height: 300px;
    padding: 10px;
    border: dotted 2px gray;
    }
    

    HTML:

    <div class=top>top </div>
    <div>
        <div class="left">left </div>
        <div class="right">
            <div class="content">right </div>
        </div>
    </div>
    

    当窗口缩小时,此方法不会自动换行,但会自动展开“内容”区域。它将保持站点菜单的静态宽度(左)。

    对于自动展开内容框和左垂直框(站点菜单)演示:

    https://jsfiddle.net/tidan/332a6qte/

        17
  •  0
  •   Ari    9 年前

    尝试添加位置 relative 移除 width float 右侧的属性,然后添加 left right 属性与 0 价值。

    此外,您还可以添加 margin left 带值的规则基于左侧元素的宽度 (如果您需要中间的空间,请加上一些像素) 保持其位置。

    这个例子对我很有用:

       #search {
            width: 160px;
            height: 25px;
            float: left;
            background-color: #FFF;
        }
    
        #navigation {  
            display: block;  
            position: relative;
            left: 0;
            right: 0;
            margin: 0 0 0 166px;             
            background-color: #A53030;
        }
    
        18
  •  0
  •   Spoorthi    9 年前

    .container {
      width:100%;
      display:table;
      vertical-align:middle;
    }
    
    .left {
      width:100%;
      display:table-cell;
      text-align:center;
    }
    
    .right {
      width:40px;
      height:40px;
      display:table-cell;
      float:right;
    }
    <div class="container">
      <div class="left">Left</div>
      <div class="right">Right</div>
    </div

    试试这个。这对我很有用。

        19
  •  0
  •   Buksy    8 年前

    我想知道没有人用过 position: absolute 具有 position: relative

    因此,另一个解决方案是:

    HTML

    <header>
      <div id="left"><input type="text"></div>
      <div id="right">Menu1 Menu2 Menu3</div>
    </header>
    

    CSS

    header { position: relative;  }
    #left {
        width: 160px;
        height: 25px;
    }
    #right {
        position: absolute;
        top: 0px;
        left: 160px;
        right: 0px;
        height: 25px;
    }
    

    Jsfiddle example

        20
  •  0
  •   colxi    6 年前

    你可以使用网格的CSS属性,这是最清晰、最干净和最直观的方式来构造你的盒子。

    #container{
        display: grid;
        grid-template-columns: 100px auto;
        color:white;
    }
    #fixed{
      background: red;
      grid-column: 1;
    }
    #remaining{
      background: green;
      grid-column: 2;
    }
    <div id="container">
      <div id="fixed">Fixed</div>
      <div id="remaining">Remaining</div>
    </div>
        21
  •  0
  •   Botea Florin    6 年前

    默认情况下,html table元素使其成为…定义表格宽度后,列将始终横跨整个表格宽度。剩下的是想象力

        22
  •  0
  •   Dmytro Yurchenko    5 年前

    物品和容器规则;

    Container: {*** display: table; ***}
    Items: {*** display: table-cell; width: 100%; ***}
    

    使用 空白:nowrap; 对于最后一个项目中的文本,因为它们是非结构化的。

    项目X%项目Y%项目Z%

    总长度始终=100%!

    如果

    Item X=50%
    Item Y=10%
    Item z=20%
    

    然后

    项目x=70%

    项x是主项(第一个项在表css布局中是主项)!

    尝试 最大含量; 容器中用于展开DIV的DIV内部属性:

    div[class="item"] {
    ...
      width: -webkit-max-content;
      width: -moz-max-content;
      width: max-content;
    ...
    

    }

        23
  •  -1
  •   Jim Dandy BOA    7 年前

    我已经研究这个问题两天了,我有一个解决方案,可以为你和任何其他人,试图作出一个响应的固定宽度左边,并让右边填写屏幕的其余部分,而不围绕左边。我假设的目的是让页面在浏览器和移动设备中响应。

    这是密码

    // Fix the width of the right side to cover the screen when resized
    $thePageRefreshed = true;
    // The delay time below is needed to insure that the resize happens after the window resize event fires
    // In addition the show() helps.  Without this delay the right div may go off screen when browser is refreshed 
    setTimeout(function(){
        fixRightSideWidth();
        $('.right_content_container').show(600);
    }, 50);
    
    // Capture the window resize event (only fires when you resize the browser).
    $( window ).resize(function() {
        fixRightSideWidth();
    });
    
    function fixRightSideWidth(){
        $blockWrap = 300; // Point at which you allow the right div to drop below the top div
        $normalRightResize = $( window ).width() - $('.left_navigator_items').width() - 20; // The -20 forces the right block to fall below the left
        if( ($normalRightResize >= $blockWrap) || $thePageRefreshed == true ){
            $('.right_content_container').width( $normalRightResize );
            $('.right_content_container').css("padding-left","0px");
            
            /* Begin test lines these can be deleted */
            $rightrightPosition = $('.right_content_container').css("right");
            $rightleftPosition = $('.right_content_container').css("left");
            $rightwidthPosition = $('.right_content_container').css("width");
            $(".top_title").html('window width: '+$( window ).width()+"&nbsp;"+'width: '+$rightwidthPosition+"&nbsp;"+'right: '+$rightrightPosition);
            /* End test lines these can be deleted */
        
        
        }
        else{
            if( $('.right_content_container').width() > 300 ){
                $('.right_content_container').width(300);
            }
            
            /* Begin test lines these can be deleted */
            $rightrightPosition = $('.right_content_container').css("right");
            $rightleftPosition = $('.right_content_container').css("left");
            $rightwidthPosition = $('.right_content_container').css("width");
            $(".top_title").html('window width: '+$( window ).width()+"&nbsp;"+'width: '+$rightwidthPosition+"&nbsp;"+'right: '+$rightrightPosition);
            /* End test lines these can be deleted */
        
        }
        if( $thePageRefreshed == true ){
            $thePageRefreshed = false;
        }
    }
    /* NOTE: The html and body settings are needed for full functionality
    and they are ignored by jsfiddle so create this exapmle on your web site
    */
    html {
        min-width: 310px;
        background: #333;
        min-height:100vh;
    }
    
    body{
    	background: #333;
    	background-color: #333;
    	color: white;
        min-height:100vh;
    }
    
    .top_title{
      background-color: blue;
      text-align: center;
    }
    
    .bottom_content{
    	border: 0px;
    	height: 100%;
    }
    
    .left_right_container * {
        position: relative;
        margin: 0px;
        padding: 0px;
        background: #333 !important;
        background-color: #333 !important;
        display:inline-block;
        text-shadow: none;
        text-transform: none;
        letter-spacing: normal;
        font-size: 14px;
        font-weight: 400;
        font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif;
        border-radius: 0;
        box-sizing: content-box;
        transition: none;
    }
    
    .left_navigator_item{
    	display:inline-block;
    	margin-right: 5px;
    	margin-bottom: 0px !important;
    	width: 100%;
    	min-height: 20px !important;
    	text-align:center !important;
    	margin: 0px;
    	padding-top: 3px;
    	padding-bottom: 3px;
    	vertical-align: top;
    }
    
    .left_navigator_items {
        float: left;
        width: 150px;
    }
    
    .right_content_container{
        float: right;
        overflow: visible!important;
        width:95%; /* width don't matter jqoery overwrites on refresh */
        display:none;
        right:0px;
    }
    
    .span_text{
    	background: #eee !important;
    	background-color: #eee !important;
    	color: black !important;
    	padding: 5px;
    	margin: 0px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <div class="top_title">Test Title</div>
    <div class="bottom_content">
        <div class="left_right_container">
            <div class="left_navigator_items">
                <div class="left_navigator_item">Dashboard</div>
                <div class="left_navigator_item">Calendar</div>
                <div class="left_navigator_item">Calendar Validator</div>
                <div class="left_navigator_item">Bulletin Board Slide Editor</div>
                <div class="left_navigator_item">Bulletin Board Slide Show (Live)</div>
                <div class="left_navigator_item">TV Guide</div>
            </div>
            <div class="right_content_container">
                <div class="span_text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ullamcorper maximus tellus a commodo. Fusce posuere at nisi in venenatis. Sed posuere dui sapien, sit amet facilisis purus maximus sit amet. Proin luctus lectus nec rutrum accumsan. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Ut fermentum lectus consectetur sapien tempus molestie. Donec bibendum pulvinar purus, ac aliquet est commodo sit amet. Duis vel euismod mauris, eu congue ex. In vel arcu vel sem lobortis posuere. Cras in nisi nec urna blandit porta at et nunc. Morbi laoreet consectetur odio ultricies ullamcorper. Suspendisse potenti. Nulla facilisi.
    
    Quisque cursus lobortis molestie. Aliquam ut scelerisque leo. Integer sed sodales lectus, eget varius odio. Nullam nec dapibus lorem. Aenean a mattis velit, ut porta nunc. Phasellus aliquam volutpat molestie. Aliquam tristique purus neque, vitae interdum ante aliquam ut.
    
    Pellentesque quis finibus velit. Fusce ac pulvinar est, in placerat sem. Suspendisse nec nunc id nunc vestibulum hendrerit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Mauris id lectus dapibus, tempor nunc non, bibendum nisl. Proin euismod, erat nec aliquet mollis, erat metus convallis nulla, eu tincidunt eros erat a lectus. Vivamus sed mattis neque. In vitae pellentesque mauris. Ut aliquet auctor vulputate. Duis eleifend tincidunt gravida. Sed tincidunt blandit tempor.
    
    Duis pharetra, elit id aliquam placerat, nunc arcu interdum neque, ac luctus odio felis vitae magna. Curabitur commodo finibus suscipit. Maecenas ut risus eget nisl vehicula feugiat. Sed sed bibendum justo. Curabitur in laoreet dolor. Suspendisse eget ligula ac neque ullamcorper blandit. Phasellus sit amet ultricies tellus.
    
    In fringilla, augue sed fringilla accumsan, orci eros laoreet urna, vel aliquam ex nulla in eros. Quisque aliquet nisl et scelerisque vehicula. Curabitur facilisis, nisi non maximus facilisis, augue erat gravida nunc, in tempus massa diam id dolor. Suspendisse dapibus leo vel pretium ultrices. Sed finibus dolor est, sit amet pharetra quam dapibus fermentum. Ut nec risus pharetra, convallis nisl nec, tempor nisl. Vivamus sit amet quam quis dolor dapibus maximus. Suspendisse accumsan sagittis ligula, ut ultricies nisi feugiat pretium. Cras aliquam velit eu venenatis accumsan. Integer imperdiet, eros sit amet dignissim volutpat, tortor enim varius turpis, vel viverra ante mauris at felis. Mauris sed accumsan sapien. Interdum et malesuada fames ac ante ipsum primis in faucibus. Ut vel magna commodo, facilisis turpis eu, semper mi. Nulla massa risus, bibendum a magna molestie, gravida maximus nunc.</div>
            </div>
        </div>
    </div>

    这是我的小提琴,可以像它对我一样对你有用。 https://jsfiddle.net/Larry_Robertson/62LLjapm/

        24
  •  -2
  •   J. Peterson    12 年前

    我也遇到了同样的问题 jqueryUI 控制。尽管现在普遍的哲学是“使用 DIV 而不是 TABLE “,我发现在我的案例中,使用表的效果要好得多。特别是,如果您需要在两个元素内进行直接对齐(例如,垂直居中、水平居中等),表格中提供的选项提供了简单、直观的控制。

    我的解决方案是:

    <html>
    <head>
      <title>Sample solution for fixed left, variable right layout</title>
      <style type="text/css">
        #controls {
          width: 100%;
        }
        #RightSide {
          background-color:green;
        }
      </style>
    </head>
    
    <body>
    <div id="controls">
      <table border="0" cellspacing="2" cellpadding="0">
        <TR>
          <TD>
            <button>
    FixedWidth
            </button>
          </TD>
          <TD width="99%" ALIGN="CENTER">
            <div id="RightSide">Right</div>
          </TD>
        </TR>
      </table>
    </div>
    </body>
    </html>
    
        25
  •  -2
  •   Bobo    9 年前

    新的CSS。但我通过使用内联块解决了这个问题。看看这个: http://learnlayout.com/inline-block.html