What does the CSS rule “clear: both” do?

前端 未结 5 1544
轮回少年
轮回少年 2020-11-21 07:42

What does the following CSS rule do:

.clear { clear: both; }

And why do we need to use it?

5条回答
  •  一个人的身影
    2020-11-21 08:05

    The clear property indicates that the left, right or both sides of an element can not be adjacent to earlier floated elements within the same block formatting context. Cleared elements are pushed below the corresponding floated elements. Examples:

    clear: none; Element remains adjacent to floated elements

    body {
      font-family: monospace;
      background: #EEE;
    }
    .float-left {
      float: left;
      width: 60px;
      height: 60px;
      background: #CEF;
    }
    .float-right {
      float: right;
      width: 60px;
      height: 60px;
      background: #CEF;
    }
    .clear-none {
      clear: none;
      background: #FFF;
    }
    float: left;
    float: right;
    clear: none;

    clear: left; Element pushed below left floated elements

    body {
      font-family: monospace;
      background: #EEE;
    }
    .float-left {
      float: left;
      width: 60px;
      height: 60px;
      background: #CEF;
    }
    .float-right {
      float: right;
      width: 60px;
      height: 120px;
      background: #CEF;
    }
    .clear-left {
      clear: left;
      background: #FFF;
    }
    float: left;
    float: right;
    clear: left;

    clear: right; Element pushed below right floated elements

    body {
      font-family: monospace;
      background: #EEE;
    }
    .float-left {
      float: left;
      width: 60px;
      height: 120px;
      background: #CEF;
    }
    .float-right {
      float: right;
      width: 60px;
      height: 60px;
      background: #CEF;
    }
    .clear-right {
      clear: right;
      background: #FFF;
    }
    float: left;
    float: right;
    clear: right;

    clear: both; Element pushed below all floated elements

    body {
      font-family: monospace;
      background: #EEE;
    }
    .float-left {
      float: left;
      width: 60px;
      height: 60px;
      background: #CEF;
    }
    .float-right {
      float: right;
      width: 60px;
      height: 60px;
      background: #CEF;
    }
    .clear-both {
      clear: both;
      background: #FFF;
    }
    float: left;
    float: right;
    clear: both;

    clear does not affect floats outside the current block formatting context

    body {
      font-family: monospace;
      background: #EEE;
    }
    .float-left {
      float: left;
      width: 60px;
      height: 120px;
      background: #CEF;
    }
    .inline-block {
      display: inline-block;
      background: #BDF;
    }
    .inline-block .float-left {
      height: 60px;
    }
    .clear-both {
      clear: both;
      background: #FFF;
    }
    float: left;
    display: inline-block;
    float: left;
    clear: both;

提交回复
热议问题