【问题标题】:How to make a div's width stretch between two divs如何使两个div之间的div宽度拉伸
【发布时间】:2014-03-13 23:59:28
【问题描述】:

我目前的问题是我有三个 div 元素;一个向左浮动,一个向右浮动,一个在这两者之间。我希望中心 div 自动拉伸到两个 div 之间可用宽度的最大宽度。

HTML

<div id="contain">
    <div id="left">1</div>
    <div id="filler"></div>
    <div id="right">2</div>
</div>

CSS

#left {
    text-decoration: none;
    display: inline-block;
    float: left;
    width: auto;
    padding: 0px 20px 0px 20px;
    height: 45px;
    text-align: center;
    line-height: 300%;
    background: #FF9000;
    color: #FFFFFF;
}
#navFiller {
    display: inline-block;
    position: fixed;
    float: left;
    width: auto;
    height: 45px;
    background: #FF9000;
}
#right {
    text-decoration: none;
    display: inline-block;
    float: right;
    width: auto;
    padding: 0px 20px 0px 20px;
    height: 45px;
    text-align: center;
    line-height: 300%;
    background: #FF9000;
    color: #FFFFFF;
}
#contain {
    width: 100%;
    height: 45px;
    padding: 0;
    margin: 0;
    display: inline;
}

项目的Jsfiddle:

http://jsfiddle.net/msEBU/

【问题讨论】:

标签: css html


【解决方案1】:

如果你在浮动元素之后添加填充元素,然后稍微改变它的样式(包括为样式块提供正确的 id),你可以得到你想要的:

#left {
  display: inline-block;
  float: left;
  padding: 0px 20px 0px 20px;
  height: 45px;
  text-align: center;
  line-height: 300%;
  background: #FF9000;
  color: #FFFFFF;
}
#filler {
  display: block;
  float: none;
  height: 45px;
  background: #F00;
}
#right {
  display: inline-block;
  float: right;
  padding: 0px 20px 0px 20px;
  height: 45px;
  text-align: center;
  line-height: 300%;
  background: #FF9000;
  color: #FFFFFF;
}
#contain {
  width: 100%;
  height: 45px;
  padding: 0;
  margin: 0;
  display: inline;
}
<div id="contain">
  <div id="left">1</div>
  <div id="right">2</div>
  <div id="filler">m</div>
</div>

或者,模拟一个表格:

 #contain {
   width: 100%;
   padding: 0;
   margin: 0;
   display: table;
 }
 #left,
 #right {
   text-decoration: none;
   display: table-cell;
   width: 5%;
   text-align: center;
   background: #FF9000;
   color: #FFFFFF;
   padding: 2% 0;
 }
 #filler {
   display: table-cell;
   width: auto;
   background: #F00;
 }
<div id="contain">
  <div id="left">1</div>
  <div id="filler">m</div>
  <div id="right">2</div>
</div>

这两种方法都有其优点。由你决定哪一个适合你。

【讨论】:

  • 谢谢!我刚刚将它添加到我的项目中,并且效果很好!
  • 您实际上并不需要 table-row 元素:stackoverflow.com/questions/16120957/…
  • 我本来打算接受的,但是 SO 不让我等 3 分钟,所以我有点分心了。
【解决方案2】:

许多 CSS 实现不支持不同浮动层之间的自动调整大小关系。虽然有很多解决方案。我的建议是使用少量的 javascript。我使用了以下 Jquery 行和一些小的 CSS 调整:

$('#filler').outerWidth($('#contain').width()-$('#right').outerWidth()-$('#left').outerWidth());

小提琴: http://jsfiddle.net/K9C4u/2/

还请注意,我将 div 移动到同一行,因为它为每个 return+tabs 创建了一个带有空格的文本节点。

【讨论】:

    猜你喜欢
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多