子级div设置margin属性影响父级位置
前端开发中,有时候会遇到设置子级div的margin属性后,导致整个父级div整体移动,有时候却是正常的,时而正常时而有异常。
一、问题描述:
1、css未设置margin属性时,效果图如下:
没有margin设置
2、css设置 margin-top:50px 属性时,预期效果图如下:
预期效果图
3、css设置 margin-top:50px 属性时,实际效果图如下:
子级margin设置
二、解决方案:
1、 给父级增加padding属性
.父级class{ padding: 10px;// 任意值都可以 }
2、给父级增加border属性
.父级class{ border: 1px solid transparent;// 是否有颜色自行处理 }
三、产生问题原因:
一个盒子如果没有上补白(padding-top)和上边框(border-top),那么这个盒子的上边距会和其内部文档流中的第一个子元素的上边距重叠。、
复现代码:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<style>
html,body{
width:100%;
height:100%;
}
.content{
width:40%;
height:40%;
position: relative;
border: 1px solid transparent; //为了解决文中所说问题
}
span {
position: absolute;
padding: 2px;
border-style: solid;
border-color: #04384e;
}
.row1 {
border-width: 2px 0 0 2px;
top: -2px;
left: -2px;
}
.row2 {
border-width: 2px 2px 0 0;
top: -2px;
right: -2px;
}
.col1 {
border-width: 0 0 2px 2px;
bottom: -2px;
left: -2px;
}
.col2 {
border-width: 0 2px 2px 0;
bottom: -2px;
right: -2px;
}
.title {
font-size: 16px;
color: #3cbeda;
height: 28px;
line-height: 28px;
margin: 15px;
padding-left: 10px;
border-left: 5px solid #05c8e8;
text-indent: 10px;
background: rgba(5, 76, 107, 0.5);
background-clip: content-box;
}
style>
head>
<body>
<div class="content">
<span class="row1">span>
<span class="row2">span>
<span class="col2">span>
<span class="col1">span>
<div class="title">
二级单位接入进度排名
div>
div>
body>
html>
效果图如下: