关于html:如何使div填充剩余的水平空间?

How to make a div fill a remaining horizontal space?

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

1
2
3
4
5
6
7
8
9
10
11
    #search {
        width: 160px;
        height: 25px;
        float: left;
        background-color: #ffffff;
    }
    #navigation {
        width: 780px;
        float: left;  
        background-color: #A53030;
    }
1
2
Text
Navigation


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

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

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

下面是一个堆栈片段中的演示&jfiddle

1
2
3
4
5
6
7
8
9
10
11
12
#left {
  float: left;
  width: 180px;
}

#right {
  margin-left: 180px;
}

/* just to highlight divs for example*/
#left { background-color: pink; }
#right { background-color: lightgreen;}
1
2
  left  
 right

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


解决方案来自显示属性。

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

这是CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.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:

1
 

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

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


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

1
2
3
4
5
6
7
.left {
  float: left;
  width: 100px;
}
.right {
  overflow: auto;
}

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


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

1
2
3
4
5
6
7
8
9
10
11
.container {
    display: flex;
}

.left {
    width: 180px;
}

.right {
    flex-grow: 1;
}

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


这似乎完成了你的目标。

1
2
3
4
5
6
7
8
9
#left {
  float:left;
  width:180px;
  background-color:#ff0000;
}
#right {
  width: 100%;
  background-color:#00FF00;
}
1
2
3
4
    left
 
 
    right


如果您不需要与某些浏览器的旧版本兼容(例如,108或更低版本),则可以使用calc()css函数:

1
2
3
4
5
6
7
8
9
10
11
#left {
   float:left;
   width:180px;
   background-color:#ff0000;
}

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


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<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>
   
        <p>
Left
</p>
   
   
        <table><tr><td>Hello, World!</td></tr></table>
   
</body>
</html>

http://jsfiddle.net/79hps/

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

您可以通过将overflow: hidden添加到右列中轻松地解决这个问题。这将为内容和分区提供正确的宽度。此外,表将收到正确的宽度并填充剩余的可用宽度。

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

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


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<html>

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

<body>
   
       
            left
       
       


right

http://jsfiddle.net/mheqg/2600/

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


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

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

问题就在于:膨胀元件没有浮动。如果您尝试在扩展元素中嵌套浮动,那么这些"嵌套"浮动项根本就不是嵌套的;当您尝试在"嵌套"浮动项下插入一个clear: both;时,最终也将清除顶级浮动。

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

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


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

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

使用display:flex

1
2
3
   fixed width

   remaining


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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.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;
}

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


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

1
2
3
4
.wrapper {margin-right:150px;}
.wrapper .left {float:left; width:100%; margin-right:-150px;}

.right {float:right; width:150px;}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
#container{
    display: grid;
    grid-template-columns: 100px auto;
    color:white;
}
#fixed{
  background: red;
  grid-column: 1;
}
#remaining{
  background: green;
  grid-column: 2;
}
1
2
  Fixed
  Remaining


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

CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
.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:

10

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

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

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


/**CSS*/

1
2
3
4
5
6
7
8
9
10
11
12
13
#search {
 position: absolute;
 width: 100px;
}
.right-wrapper {
  display: table;
  width: 100%;
  padding-left:100px;
}
.right-wrapper #navigation {
 display: table-cell;
 background-color: #A53030;
}

/**HTML*/

1
 

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

1
2
3
4
    left


    right

/CSS

1
2
3
4
5
6
7
8
9
#left {
float:left;
width:50%;
position:relative;
background-color:red;
}
#right {
position:relative;
background-color:#00FF00;}

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


物品和容器规则;

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

使用空白:nowrap;用于最后一个项目中的文本,用于取消其结构。

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

总长度始终=100%!

如果

10

然后

项目x=70%

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

Try max content;用于在容器中展开DIV的内部DIV属性:

1
2
3
4
5
6
div[class="item"] {
...
  width: -webkit-max-content;
  width: -moz-max-content;
  width: max-content;
...

}


尝试增加位置relative,移除右侧的widthfloat属性,然后添加leftright属性,0值。

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

这个例子对我很有用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
   #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;
    }


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.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;
}
1
2
3
  Left
  Right
</div

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


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

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

HTML

1
2
3
4
<header>
  <input type="text">
  Menu1 Menu2 Menu3
</header>

CSS

1
2
3
4
5
6
7
8
9
10
11
12
header { position: relative;  }
#left {
    width: 160px;
    height: 25px;
}
#right {
    position: absolute;
    top: 0px;
    left: 160px;
    right: 0px;
    height: 25px;
}

JSfiddle示例


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

这是密码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// 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;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/* 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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
Test Title

   
       
            Dashboard
            Calendar
            Calendar Validator
            Bulletin Board Slide Editor
            Bulletin Board Slide Show (Live)
            TV Guide
       
       
            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.

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


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


我在尝试布局一些jqueryui控件时遇到了同样的问题。尽管现在普遍的理念是"使用DIV"而不是TABLE",但我发现在我的案例中,使用table的效果要好得多。特别是,如果您需要在两个元素内进行直接对齐(例如垂直居中、水平居中等),则表格中提供的选项提供了对此的简单、直观的控制。

我的解决方案是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<html>
<head>
  Sample solution for fixed left, variable right layout
  <style type="text/css">
    #controls {
      width: 100%;
    }
    #RightSide {
      background-color:green;
    }
  </style>
</head>

<body>

  <table border="0" cellspacing="2" cellpadding="0">
    <TR>
      <TD>
        <button>
FixedWidth
        </button>
      </TD>
      <TD width="99%" ALIGN="CENTER">
        Right
      </TD>
    </TR>
  </table>

</body>
</html>


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