首页 文章

如何使div填充剩余的水平空间?

提问于
浏览
363

我有2个div:一个在左侧,一个在我的页面右侧 . 左侧的那个有固定的宽度,我希望右侧的一个填充剩余的空间 .

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

23 回答

  • 3

    这似乎可以实现您的目标 .

    #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>
    
  • 81

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

  • -2

    @ Boushley的回答是最接近的,但是有一个问题没有得到解决 . 右侧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/

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

    您可以通过将 overflow: hidden 添加到右列来轻松实现 fix this . 这为内容和div提供了正确的宽度 . 此外,表格将获得正确的宽度并填充剩余的可用宽度 .

    我尝试了上面的其他一些解决方案,它们没有完全适用于某些边缘情况,并且太复杂而无法修复它们 . 这很有效,而且很简单 .

    如果有任何问题或疑虑,请随意提出 .

  • 0

    我有一个非常简单的解决方案! // 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/

  • 245

    我遇到了同样的问题,试图布局一些jqueryUI控件 . 虽然现在常见的哲学是“使用 DIV 而不是 TABLE ”,但我发现在我的情况下使用TABLE工作得更好 . 特别是,如果您需要在两个元素中进行直接对齐(例如,垂直居中,水平居中等),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>
    
  • 0

    我在Boushley 's answer is that if the right column is longer than the left it will just wrap around the left and resume filling the whole space. This is not the behavior I was looking for. After searching through lots of ' solutions中找到的问题'我在创建三个列页时发现了这个awesome tutorial .

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

    基本上,在上面的简单情况下,将第一列向左浮动并赋予其固定宽度 . 然后在右边的列中给出一个比第一列略宽的左边距 . 而已 . 完成 . Ala Boushley的代码:

    这是 Stack SnippetsjsFiddle的演示

    #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的例子中,左列保持右边的另一列 . 一旦左列结束,右侧开始再次填充整个空间 . 右边的列只是进一步对齐页面,左列占据了它的巨大余量 . 无需流量交互 .

  • 0

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

    #left {
       float:left;
       width:180px;
       background-color:#ff0000;
    }
    
    #right {
       float: left;
       width: calc(100% - 180px);
       background-color:#00FF00;
    }
    
  • 121

    我想知道没有人用 position: absoluteposition: 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

  • 0

    这是对已接受的解决方案的一点修复,它可以防止右列落入左列 . 用 overflow: hidden; 取代 width: 100%; 是一个棘手的解决方案,如果有人不知道的话 .

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

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

  • 15

    我尝试了上面的液体离开的解决方案,固定的权利,但没有工作(我知道问题是相反的,但我认为这是相关的) . 这是做了什么工作:

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

    试试这个 . 它对我有用 .

  • 20

    我有类似的问题,我在这里找到了解决方案: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;
    }
    

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

  • 3

    尝试添加位置 relative ,删除右侧的 widthfloat 属性,然后使用 0 值添加 leftright 属性 .

    此外,您可以添加 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;
        }
    
  • 0

    / * * 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>
    
  • 12

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

    .fill {
      // This fills the remaining space, by using flexbox. 
      flex: 1 1 auto;
    }
    
  • 3

    我有一个类似的问题,并提出了以下工作得很好

    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/

  • 3

    您可以使用Grid 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>
    
  • -2

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

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

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

  • -1

    我已经在这个问题上工作了两天,并且有一个解决方案可能适合你和其他任何试图使响应固定宽度保持不变的人,并且右侧填充屏幕的其余部分而不包围左侧 . 我假设的目的是使页面在浏览器和移动设备中响应 .

    Here is the Code

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

  • 0

    使用 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>
    
  • 0

    解决方案来自display属性 .

    基本上你需要使两个div像表格单元格一样 . 因此,不必使用 float:left ,而是必须在两个div上使用 display:table-cell ,对于动态宽度div,您还需要设置 width:auto; . 应将两个div放入具有 display:table 属性的100%宽度容器中 .

    这是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上写的关于此的完整文章 .

  • 96

    Boushley的答案似乎是最好的方法,以便使用花车来安排这个 . 然而,它并非没有问题 . 您将无法使用展开元素中的嵌套浮动;它会破坏页面 .

    当涉及到扩展元素时,所显示的方法基本上是“伪造它” - 它实际上并不浮动,它只是使用其边缘与固定宽度的浮动元素一起播放 .

    那么问题就在于:扩展元素根本就没有嵌套;当你试图在你的"nested"浮动项目下粘贴 clear: both; 时,你最终也会清除顶级浮动 .

    然后,为了使用Boushley的解决方案,我想补充一点,你应该放置一个div,如下所示:.fakeFloat {height:100%;宽度:100%;向左飘浮;并将其直接放在展开的div中;所有扩展的div的内容应该在这个fakeFloat元素中 .

    出于这个原因,我建议在这种特定情况下使用表格 . 浮动元素实际上并不是为了进行扩展而设计的,而使用表格的解决方案则是微不足道的 . 通常认为浮动更适合布局,而不是表格..但是你不是在这里使用漂浮,你是假装它 - 而这种情况在这个特定情况下会破坏风格论证的目的,我的拙见 .

  • 3

    由于这是一个相当受欢迎的问题,我倾向于使用BFC分享一个很好的解决方案 .
    以下here的Codepen示例 .

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

    在这种情况下, overflow: auto 触发上下文行为并使右元素仅扩展到可用的剩余宽度,如果 .left 消失,它将自然地扩展为全宽 . 许多UI布局的一个非常有用和干净的技巧,但最初可能很难理解"why it works" .

相关问题