写网页中遇到的基本布局问题

91 阅读1分钟

不知道标题名字对不对,请各位大佬看看

一、margin塌陷问题

在一个元素里,第一个子元素的 margin-top 会塌陷给父级;最后一个子元素的 margin-bottom 会塌陷给父级。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box1{
      width: 400px;
      height: 400px;
      background-color: aliceblue;
      margin: 100px auto;
    }
    .box2{
      width: 400px;
      height: 400px;
      background-color: aqua;
    }
  </style>
</head>
<body>
  <div class="box1">
    <div class="box2"></div>
  </div>
</body>
</html>

未塌陷前:

Snipaste_2023-07-24_08-27-23.png

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box1{
      width: 400px;
      background-color: aliceblue;
      margin: 100px auto;
    }
    .box2{
      width: 100px;
      height: 100px;
      margin-top: 100px;
      margin-bottom: 200px;
      background-color: aqua;
    }
    .box3{
      width: 100px;
      height: 100px;
      margin-bottom: 100px;
      background-color: rgb(73, 149, 149);
    }
  </style>
</head>
<body>
  <div class="box1">
    <div class="box2"></div>
    <div class="box3"></div>
  </div>
</body>
</html>

塌陷后:

Snipaste_2023-07-24_08-26-42.png

解决margin塌陷问题

方法一:给父元素设置不为 0 的内边距

方法二:给父元素设置不为 0 的边框

方法三:给父元素设置CSS样式overflow:hidden

二、内容溢出

CSS 属性名功能属性值
overflow溢出内容的处理方式visible:显示,默认值
hidden:隐藏
scroll:显示滚动条,不论内容是否溢出
auto:自动显示滚动条,内容不溢出不显示
overflow-x水平方向溢出内容的处理方式同 overflow
overflow-y垂直方向溢出内容给的处理方式同 overflow

三、底部空白

图片产生幽灵空白

产生原因:

行内块元素或行内元素与文本的基线对齐,幽灵空白就是基线与底线之间的距离。

解决方案:

1、**方案一:**给行内元素设置vertical的值不为baseline即可,设置为middelbottomtop即可

2、**方案二:**给父元素设置font-size: 0。如果该行内元素或行内块元素内部还有文本内容需单独设置font-size

3、**方案三:**主要针对于图片,设置图片为display: block