【问题标题】:Let div on the leftside take up all the space [duplicate]让左侧的 div 占据所有空间[重复]
【发布时间】:2018-04-23 14:52:45
【问题描述】:

当有 2 个 div 时,一个在左边,一个在右边。 是否可以让右 div 以固定宽度一直向右对齐,并让左 div 占据所有剩余空间?

我不想使用 inline-

【问题讨论】:

  • 你只需要在左边的div上设置flex: 1

标签: html css flexbox


【解决方案1】:

您可以在此处使用 CSS calc() function.left div 中减去固定.right div 的width

calc() CSS 函数允许您在指定时执行计算 CSS 属性值。

#bx{
  background:black;
  height:200px;
  padding:10px;
}
#bx > .left{
  display:inline-block;
  width:calc(99% - 200px); /*Minus width of .right using calc()*/
  height:100%;
  background:yellow;
}
#bx > .right{
  display:inline-block;
  width:200px;
  height:100%;
  background:red;
}
<div id="bx">
  <div class="left">Left Div</div>
  <div class="right">Right Div Fixed Width.</div>
</div>

【讨论】:

  • @S. Robijns 尝试缩放上面的代码。正确的 div 保持固定。
  • 太棒了,不知道,谢谢!
  • 欢迎@S.Robijns :-)
  • 为什么要使用width: auto;,它是默认的。
  • @LGSon 我会更新的。
【解决方案2】:

有很多方法可以实现这一点,但您可能希望使用 flex-boxes,因为它现在被广泛使用。

检查caniuse,看看它是否符合您的浏览器要求。

标记:

<div class="container">
  <div class="left-container">Autofill remaining width</div>
    <div class="fixed-container">200px</div>
</div>

CSS:

.container{
  display: flex;
}
.left-container {
  background-color: red;
  flex: 1;
}
.fixed-container {
  flex-basis: 200px;
  background-color: yellow;
  text-align: center;
}

Demo

【讨论】:

  • flex 不支持低于 11 的 ie 版本,因此它不是最通用的解决方案 caniuse.com/#search=flex
  • ie10 及以下版本不受 Microsoft 支持,因此我认为这不是什么大问题 - 他们公司支持的所有最新浏览器都支持 flex
  • @RyanEarnshaw 供应商前缀 (-ms-) 可用于支持 IE10。 msdn.microsoft.com/en-us/library/hh673531(v=vs.85).aspx
  • 对最后两个 cmets 的地址访问此链接:caniuse.com/#search=flex 并阅读“注释”和“已知问题”部分。你会发现 flex 虽然有效,但只是部分有效,因为它不受支持
  • @RyanEarnshaw 由于存在大量错误,它仅在 IE 中部分工作,这与“不支持”非常不同。并且IE10支持老版本,解决了这个问题,没有bug。
【解决方案3】:

我认为这可以实现您所追求的,但我不确定它是最好的方式......

.container {
  width: 100%;
  height: 200px;
  background-color: green;
}

.sidebar {
  float: right;
  width: 200px;
  height: 200px;
  background-color: blue;
}

.content {
  background-color: red;
  height: 200px;
  margin-right: 200px;
}
<div class="sidebar">width: 200px</div>
<div class="content">
</div>

【讨论】:

  • 这似乎确实有效,但是由于内容 div 元素位于 html 中的侧边栏 div 后面,因此代码量很大,设置也很奇怪
  • 第一,你不需要width: auto;,它是默认的,第二,你使用clearfix元素,它应该定位在之后 i> 要产生效果的浮动元素。
  • 好的改变了我的答案
猜你喜欢
  • 2012-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-25
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多