为什么浮动 div 后有空格,如何删除它?

Why is there spacel after floated divs and how can I remove it?

我想使用 float: right;,但它在 div 之后变成了 space,看起来 div 有 margin-bottom,但实际上没有' t.
这是为什么?
以及如何删除 float: right; 创建的 space?

.container {
    background-color: #bbbbbb;
    width: 70%;
}

.line {
    display: inline-block;
    width: 100%;
}

.child {
    background-color: coral;
    height: 2em;
    width: 50%;
    float: right;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="container">
            <div class="line"><div class="child"></div></div>
            <div class="line"><div class="child"></div></div>
    </div>
</body>

</html>

此行为是在嵌套浮动元素 (.child) 的包含元素 (.line) 上声明 display: inline-block 属性 的结果;在兄弟元素之间创建一个“white space”。

要解决此问题,请考虑在包含元素 (.line) 上声明 vertical-align 属性,如下所示。

.line {
  display: inline-block;
  width: 100%;
  vertical-align: top; /* additional */
}

注意:由于块元素的 内联 性质, 这个 属性 值可以应用到这个元素。

代码片段演示:

.container {
  background-color: #bbbbbb;
  width: 70%;
}

.line {
  display: inline-block;
  width: 100%;
  vertical-align: top; /* additional */
}

.child {
  background-color: coral;
  height: 2em;
  width: 50%;
  float: right;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="container">
    <div class="line">
      <div class="child"></div>
    </div>
    <div class="line">
      <div class="child"></div>
    </div>
  </div>
</body>

</html>

尝试使用 display: flex;

.container {
  background-color: #bbbbbb;
  width: 70%;
}

 

.child {
  background-color: coral;
height: 3em;
width: 50%;
display: flex;
margin-left: auto;;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="container">
    <div class="line">
      <div class="child"></div>
    </div>
    <div class="line">
      <div class="child"></div>
    </div>
  </div>
</body>

</html>