分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

CSS - 外边距合并

发布时间:2023-09-06 01:53责任编辑:赖小花关键词:CSS

1. 外边距合并

当上下相邻的两个块元素相遇时,如果上面的元素有下外边距margin-bottom,下面的元素有上外边距margin-top,则他们之间的垂直间距不是margin-bottom与margin-top之和,而是两者中的较大者。这种现象被称为相邻块元素垂直外边距的合并(也称外边距塌陷)

<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<title>Document</title> ???<style> ???div { ???????width: 300px; ???????height: 200px; ???????background-color: purple; ???} ???.xiongda { ???????margin-bottom: 100px; ???} ???.xionger { ???????background-color: pink; ???????margin-top: 150px; ?/*最终两个盒子的距离是 ?最大的那个为准 ?150*/ ???} ???</style></head><body> ???<div class="xiongda">1</div> ???<div class="xionger">2</div></body></html>

解决方案:避免。

2. 嵌套块元素垂直外边距的合并(只出现在垂直和嵌套)

对于两个嵌套关系的块元素,如果父元素没有上内边距及边框,则父元素的上外边距会与子元素的上外边距发生合并,合并后的外边距为两者中的较大者,即使父元素的上外边距为0,也会发生合并。

<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<title>Document</title> ???<style> ???.father { ???????width: 500px; ???????height: 500px; ???????background-color: pink; ???????/*padding-top: 50px;*/ ???????/*border-top: 1px solid pink; 1. 用border*/ ????????/*padding-top: 1px; ??????????2 用padding */ ???????overflow: hidden; ??????????3. 用这个单词可以解决 ???} ???.son { ???????width: 200px; ???????height: 200px; ???????background-color: purple; ???????margin-top: 50px; ???????margin-left: 50px; ???} ???</style></head><body> ???<div class="father"> ???????<div class="son"></div> ???</div></body></html>

解决方案:

  1. 可以为父元素定义1像素的上边框或上内边距。
  2. 可以为父元素添加overflow:hidden。

CSS - 外边距合并

原文地址:https://www.cnblogs.com/allen2333/p/9011705.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved