relative
.box1 {width: 100px; height: 100px;background-color: antiquewhite;}
.box2 {width: 100px;height: 100px;background-color: rosybrown;position: relative;top: 50px;left: 100px;}
<div class="box1"></div>
<div style="width: 300px;height: 200px;background-color: aquamarine;padding: 10px;">
<div class="box2"></div>
<span>4564</span>
</div>
相对于自身的起点位置,只改变显示位置,(上下左右移动) ;若声明了 relative 的元素的子集需要定位,则是以父级为参照物
兄弟元素 margin 合并
重叠取值规则
1、两者都是正值,取大的值
2、一正一负,取两者的和(-10,10 取0)
3、两者为负,取绝对值大的值(-10,-20,取-20)
解决方式一(父级元素用 flex 弹性布局)常用
<style>
.aa {
display: flex;
flex-direction: column;
}
.bb {
width: 200px;
height: 200px;
border: 1px solid #333;
}
</style>
<div class="aa">
<div class="bb" style="margin-bottom: 10px;"></div>
<div class="bb" style="margin-top: 10px;"></div>
</div>
解决方式二(自身元素浮动,父级清除浮动 )
<style>
.aa {
border:1px solid red;
}
.aa::after{
content:"";
display:block;
clear:both;
}
.bb {
width: 200px;
height: 200px;
border: 1px solid #333;
float:left;
}
</style>
<div class="aa">
<div class="bb" style="margin-bottom: 10px;"></div>
<div class="bb" style="margin-top: 10px;"></div>
</div>
解决方式三(两合并元素间加一个空白 div,设为 flex)
<style>
.aa {
border:1px solid red;
}
.bb {
width: 200px;
height: 200px;
border: 1px solid #333;
}
</style>
<div class="aa">
<div class="bb" style="margin-bottom: 10px;"></div>
<div style="display: flex;"></div>
<div class="bb" style="margin-top: 10px;"></div>
</div>
父子元素 margin 击穿
解决方式一(父级加边框)大小会发生改变
<style>
.father {
border: 1px solid red;
background-color: antiquewhite;
}
</style>
<div class="father">
<div style="margin-top: 30px;height: 200px; width: 200px;border: 1px solid #333;">margin-top: 30px</div>
</div>
解决方式二(父级添加 overflow: auto 样式)auto有不可控因素
<style>
.father {
overflow: auto;
background-color: antiquewhite;
}
</style>
<div class="father">
<div style="margin-top: 30px;height: 200px; width: 200px;border: 1px solid #333;">margin-top: 30px</div>
</div>
解决方式三(父级添加伪元素)常用
table 和 block 的区别:block是定义此元素为块级元素;table 则是将元素会作为块级表格来显示(类似
<table>),表格前后带有换行符。
<style>
.father {
background-color: antiquewhite;
}
.father::before {
content: "";
display: table;
}
</style>
<div class="father">
<div style="margin-top: 30px;height: 200px; width: 200px;border: 1px solid #333;">margin-top: 30px</div>
</div>
解决方式四(父级添加 flex 属性 或 inline-block)
<style>
.father {
background-color: antiquewhite;
display: inline-block;
/* display: flex; */
}
</style>
<div class="father">
<div style="margin-top: 30px;height: 200px; width: 200px;border: 1px solid #333;">margin-top: 30px</div>
</div>