我正在尝试使用部分来布局页面,但是遇到了一些问题。我的代码如下...

https://jsfiddle.net/ytv4zp4b/

<section>
    <div class="width">
        Test Content
                <div class="sharing">
            <div class="sharingsocial">
                Social Links
            </div>
            <div class="sharingprint">
                Print Link
            </div>
        </div>
    </div>
</section>
<section>
    Footer
</section>

section{background-color:grey;}
.width{background-color:red;max-width:500px;margin:auto;}
.sharing{max-width:500px;margin:auto;}
.sharingsocial{float:left;background:green;}
.sharingprint{float:right;background:yellow;}


我无法弄清楚为什么.sharing div被页脚部分覆盖,我在哪里出错?

最佳答案

问题

CSS float属性导致所有后续元素也浮动。有关浮点数的更多信息,请参见here

解决方案

您还必须设置clear: both才能停止其他元素的浮动。

您可以通过将以下内容添加到CSS中来完成此操作:

.width:after {
    content: '';
    display: block;
    clear: both;
}


演示版



section{
  background-color: grey;
}

.width{
  background-color:red;
  max-width:500px;
  margin:auto;
  }

.width:after {
    content: '';
    display: block;
    clear: both;
}

.sharing{
  max-width:500px;
  margin:auto;
}

.sharingsocial{
  float:left;
  background:green;
}
.sharingprint{
  float:right;
  background:yellow;
}

<section>
    <div class="width">
        Test Content
	<div class="sharing">
            <div class="sharingsocial">
                Social Links
            </div>
            <div class="sharingprint">
                Print Link
            </div>
        </div>
    </div>
</section>
<section>
    Footer
</section>

10-05 20:45
查看更多