zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

前端面试 【CSS】— 使用 display:inline-block 会产生什么问题?解决方法?

2023-03-14 22:48:07 时间

1. 产生的问题描述

两个display为inline-block元素放到一起会产生一段空白。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .container {
      width: 800px;
      height: 200px;
    }

    .left {
      font-size: 14px;
      background: red;
      display: inline-block;
      width: 100px;
      height: 100px;
    }

    .right {
      font-size: 14px;
      background: blue;
      display: inline-block;
      width: 100px;
      height: 100px;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="left">左</div>
    <div class="right">右</div>
  </div>
</body>

</html>

如上代码所示,运行后效果如下:

2. 问题产生的原因

元素被当成行内元素排版的时候,元素之间的空白符都会被浏览器处理,根据CSS中 white-space 属性的处理方式(默认是normal,合并多余空白),原来HTML代码中的回车换行被转成一个空白符,在字体不为0的情况下,空白符占据一定宽度,所以 inline-block 的元素之间就出现了空隙。

3. 问题的解决办法

1. 将子元素标签的结束符和下一个标签的开始符写在同一行 或 把所有子标签写在同一行;

<div class="container">
  <div class="left">
      左
  </div><div class="right">
      右
  </div>
</div>

2. 父元素中设置font-size为0,在子元素上重置正确的 font-size;

<style>
  .container {
    width: 800px;
    height: 200px;
    /* 父元素字体设置为0 */
    font-size: 0;
  }

  .left {
    font-size: 14px;
    background: red;
    display: inline-block;
    width: 100px;
    height: 100px;
  }

  .right {
    font-size: 14px;
    background: blue;
    display: inline-block;
    width: 100px;
    height: 100px;
  }
</style>

<div class="container">
  <div class="left">左</div>
  <div class="right">右</div>
</div>

3. 为子元素设置float为left;

<style>
  .container {
    width: 800px;
    height: 200px;
  }
  .left {   
    /* 添加浮动 */
    float:left;
    font-size: 14px;
    background: red;
    display: inline-block;
    width: 100px;
    height: 100px;
  }

  .right {
    /* 添加浮动 */
    float:left;
    font-size: 14px;
    background: blue;
    display: inline-block;
    width: 100px;
    height: 100px;
  }
</style>

<div class="container">
  <div class="left">左</div>
  <div class="right">右</div>
</div>