如何使用Clearfix解决浮动问题

时间:2019-05-02 07:04:45

标签: html css

我已经用CSS构建了一个正方形,但是却遇到了浮动问题。我使用clearfix方法,但我想我在CSS中犯了一个小错误。

@hide

这里是Fiddle

1 个答案:

答案 0 :(得分:1)

您需要在文章规则中使用box-sizing:border-box。下面的示例:

body {
  margin: 0;
}

article:before {
  clear: left;
}

article {
  border: 2px solid #ccc;
  float: left;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

article:nth-of-type(1) {
  background-color: red;
  width: 50%;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

article:nth-of-type(2) {
  background-color: blue;
  width: 50%;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

article:nth-of-type(3) {
  background-color: grey;
  width: 50%;
  height: 100px;
  text-align: center;
  clear: left;
  line-height: 100px;
}

article:nth-of-type(4) {
  background-color: green;
  width: 50%;
  height: 100px;
  text-align: center;
  line-height: 100px;
}
<article>1</article>
<article>2</article>
<article>3</article>
<article>4</article>