如何填充对齐块的背景?

时间:2012-11-27 00:39:04

标签: css layout css-float

我有以下代码:

<div style="background-color:Aqua">
    <div style="float:left">left</div>
    <div style="float:right">right</div>
</div>

我想要显示......

left                                                                        right

......有浅绿色背景,但积木没有填充颜色。

我做错了什么?

3 个答案:

答案 0 :(得分:0)

清除您的花车,例如使用overflow: hidden

<div style="background-color:Aqua; overflow: hidden">
    <div style="float:left">left</div>
    <div style="float:right">right</div>
</div>

答案 1 :(得分:0)

浮动 - 定位的规则取决于某些东西,所以如果没有这个东西你永远不会对齐。 因此,您应该使用以下序列:

<div style="background-color:Aqua">
  <div style="float:right;max-width:50%;">Right</div><!-- 100% by default -->
  <div>Left</div>
  <div style="clear:right;"></div><!-- closing the floating -->
</div>

以及其他方式:

<div style="background-color:Aqua">
  <div style="float:left;max-width:50%;">Left</div>
  <div>Right</div>
  <div style="clear:left;"></div>
</div>

或两者:

<div style="background-color:Aqua">
  <div style="float:left;max-width:30%;">Left</div>
  <div style="float:right;max-width:30%;">Right</div>
  <div>Center</div>
  <div style="clear:both;"></div>
</div>

答案 2 :(得分:0)

我建议使用强大的clearfix,尤其是这个:http://www.yuiblog.com/blog/2010/09/27/clearfix-reloaded-overflowhidden-demystified/

添加此CSS:

.clearfix:before,
.clearfix:after {
  content: ".";    
  display: block;    
  height: 0;    
  overflow: hidden; 
}
.clearfix:after {clear: both;}
.clearfix {zoom: 1;} /* IE < 8 */

然后给你的包含父水族div class="clearfix"

这是fiddle demonstration