476

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

4

26 回答 26

284

我在 Boushley 的回答中发现的问题是,如果右列比左列长,它只会环绕左列并继续填充整个空间。这不是我想要的行为。在搜索了很多“解决方案”后,我找到了一个关于创建三栏页面的教程(现在链接已失效)。

作者提供了三种不同的方式,一种是固定宽度,一种是三列可变列,一种是外列固定,中间宽度可变。比我发现的其他示例更优雅、更有效。大大提高了我对 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 的示例中,左列将另一列保留在右侧。一旦左列结束,右列就开始再次填充整个空间。在这里,右列只是进一步对齐页面,左列占据了它的大页边距。无需流交互。

于 2011-05-10T19:20:22.630 回答
206

这些天,您应该使用该flexbox方法(可能适用于所有带有浏览器前缀的浏览器)。

.container {
    display: flex;
}

.left {
    width: 180px;
}

.right {
    flex-grow: 1;
}

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

于 2014-08-04T11:31:52.787 回答
134

解决方案来自显示属性。

基本上你需要让两个 div 像表格单元格一样工作。float:left因此,您必须在两个 div 上都使用,而不是 using ,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 属性,否则将无法填充空间。

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

于 2011-03-24T09:13:20.633 回答
112

由于这是一个相当受欢迎的问题,我倾向于使用 BFC 分享一个不错的解决方案。
下面的 Codepen 示例在这里

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

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

于 2014-06-27T15:21:41.423 回答
78

这似乎完成了你的目标。

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

于 2009-06-23T14:35:14.143 回答
24

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

#left {
   float:left;
   width:180px;
   background-color:#ff0000;
}

#right {
   float: left;
   width: calc(100% - 180px);
   background-color:#00FF00;
}
于 2015-09-28T14:38:02.053 回答
16

@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%带在铬)。

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

我尝试了上面的一些其他解决方案,它们不能完全处理某些边缘情况,而且太复杂以至于无法修复它们。这很有效,而且很简单。

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

于 2012-04-18T23:24:36.063 回答
12

这是针对已接受解决方案的一个小修复,可防止右列落在左列之下。如果有人不知道,则替换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/

于 2015-10-04T15:05:30.140 回答
5

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

.fill {
  // This fills the remaining space, by using flexbox. 
  flex: 1 1 auto;
}
于 2016-11-17T16:32:31.870 回答
4

采用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>
于 2016-12-21T13:45:04.050 回答
3

Boushley 的回答似乎是最好的方式来安排这个使用浮动。然而,它并非没有问题。您将无法使用展开元素内的嵌套浮动;它会打破页面。

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

那么问题就在于:扩展元素没有浮动。如果您尝试在扩展元素中使用任何嵌套浮动,则那些“嵌套”浮动项根本不是真正嵌套的;当您尝试clear: both;在“嵌套”浮动项目下粘贴 a 时,您最终也会清除顶级浮动。

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

出于这个原因,我建议在这种特定情况下使用表格。浮动元素确实不是为了进行您想要的扩展而设计的,而使用表格的解决方案是微不足道的。通常有人认为浮动更适合于布局,而不是表格。但无论如何你都没有在这里使用浮动,你在伪造它——这有点违背了这种特定情况下风格论点的目的,在我的拙见。

于 2011-08-30T21:06:00.570 回答
3

我尝试了上述针对液体左侧的解决方案,以及一个固定的右侧但它们都不起作用(我知道问题是相反的,但我认为这是相关的)。这是有效的:

.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>
于 2012-11-23T14:49:00.733 回答
3

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

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

于 2014-11-07T15:20:16.463 回答
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>

于 2018-10-10T21:33:43.553 回答
1

我想知道没有人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 示例

于 2016-02-16T08:13:48.380 回答
1

如果有人需要相同的解决方案但没有左 div 的固定长度:

如果您希望左侧 div 占据它需要的所有空间,您可以删除固定大小 180px。请参阅下面的 CSS:

#left {
  float: left;
  background-color: red;
}

#right {
  background-color: yellow;
  flex-grow: 1
}

在 JSFiddle 中看到这里:jsfiddle-div-space

于 2021-07-27T14:34:19.350 回答
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>
于 2013-11-08T13:55:13.450 回答
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/

于 2015-05-22T04:46:00.913 回答
0

我有一个类似的问题,并想出了以下效果很好

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/

于 2015-08-05T19:38:53.063 回答
0

尝试添加右侧的位置relative,删除width和属性,然后添加和属性值。floatleftright0

此外,您可以添加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;
    }
于 2015-10-04T12:31:30.730 回答
0

.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

试试这个。它对我有用。

于 2015-10-09T14:27:39.790 回答
0

我已经解决这个问题两天了,并且有一个可能适用于您和其他任何人的解决方案,该解决方案可能会为您和其他任何人尝试制作一个响应式固定宽度左侧并让右侧填充屏幕的其余部分而不环绕左侧。我假设的目的是使页面在浏览器和移动设备中响应。

这是代码

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

于 2018-01-10T03:44:12.337 回答
0

物品和容器规则;

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

}

于 2019-02-24T01:49:24.940 回答
0

最简单的解决方案是让左 div 宽度等于 100% - 右 div 的宽度加上它们之间的任何边距。

<div class="cont">
  <div class="search">
    Big Logo Text
  </div>
  <nav>
    <ul class="navbar">
      <li><a href="#1">NavLink1</a></li>
      <li><a href="#2">NavLink2</a></li>
      <li><a href="#3">NavLink3</a></li>
      <li><a href="#4">NavLink4</a></li>
      <li><a href="#5">NavLink5</a></li>
    </ul>
  </nav>
</div>

.cont{
  display: inline-grid;
  grid-template-columns: 160px 10px calc(100% - 170px);
  grid-template-rows: auto;
  grid-template-areas: "search .  navigation";
  width: 100%;
  height: auto;
  text-align: center;
}

.search {
  grid-area: search;
  height: 90px;
  background-color: #00FF00;
  line-height: 80px;
  font-size: 1.4rem;
  font-weight: 600;
}
nav {
  grid-area: navigation;
  height: 90px;
  background-color: #A53030;
}

.navbar{
  display: flex;
  height: 30px;
  width: 100%;
  padding: 0%;
  list-style-type: none;
  flex-flow: row wrap;
  flex: 0 1 auto;
  justify-content: space-between;
  align-content: flex-start;
  align-items: flex-start;
}

.navbar a{
    outline: 0;
    text-decoration: none;
}

https://codepen.io/tamjk/pen/dybqKBN

于 2019-09-17T14:10:55.010 回答
0

最简单的解决方案是使用保证金。这也将响应!

<div style="margin-right: auto">left</div>
<div style="margin-left: auto; margin-right:auto">center</div>
<div style="margin-left: auto">right</div>
于 2019-11-08T20:38:55.267 回答
-2

我在尝试布局一些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>
于 2012-04-04T22:21:41.417 回答