外边距-margin
外边距\外间距
margin特征:
- 位于边框border之外
- margin值是添加给自身的, 调整元素自身的位置或者调整元素与元素于元素之间的位置
- margin不会撑大盒子
- margin在页面中没有颜色
- 在谷歌f12中显示橘黄色
- marign支持负值
margin属性:
单边外边距属性
- margin-方位词(top\right\bottom\left)
1-4边的外边距
- 一个值 四边
- 两个值上下 左右
- 三个值上 左右 下
- 四个值上右下 左
<style>
.box1{
background-color: pink;
width: 100px;
height: 100px;
padding: 20px;
border: 10px solid red;
/* 1-4边的外边距 */
/* 1-4边 */
margin: 80px;
/* 1-上下 2-左右 */
margin: 80px 10px;
/* 1-上 2-左右 3-下 */
margin: 80px 10px 40px;
/* 1234-上右下左 */
margin: 80px 90px 70px 30px;
}
</style>
<div class="box1"></div>
谷歌浏览器检查
外边距溢出
外边距溢出是父元素里面的第一个子元素添加marign-top,会把父元素带下来
原因:父元素盒子元素共用了margin
解决:
- 给父元素添加1px的border:1px solid transparent
- 给父元素添加1px的padding-top:1px
- 给父元素添加overflow: hidden(触发了BFC)
小结: 方法1\2都会撑大盒子, 建议使用方法3
<style>
.father{
width: 100px;
height: 100px;
background-color: bisque;
/* padding-top: 1px; */
/* border: 1px solid transparent; */
overflow: hidden;
}
.son{
width: 50px;
height: 50px;
background-color: pink;
margin-top: 30px;
}
</style>
<div class="father">
<div class="son"></div>
</div>
外边距合并
垂直方向: 相邻的上下两个元素, 上面有margin-bottom, 下面有marign-top, 垂直外边距相遇, 间距发生重叠, 以数值大的为准
解决:
- 间距写单方向即可(单边外边距)
<style>
div{
width: 100px;
height: 100px;
background-color: pink;
}
p{
height: 100px;
width: 100px;
margin-top: 60px;
background-color: skyblue;
}
</style>
<div>div</div>
<p>p</p>
水平方向: 外边距相加 左右两个兄弟元素之间, 外边距相遇会相加
<style>
*{
padding: 0;
margin: 0;
}
div{
width: 100px;
height: 100px;
background-color: pink;
float: left;
margin-right: 30px;
}
p{
height: 100px;
width: 100px;
background-color: skyblue;
float: left;
margin-left: 20px;
}
</style>
<div>div</div>
<p>p</p>
水平居中
独占一行的元素水平居中
- 给自身设置, 为了调整元素与元素之间的位置
- margin: auto
- margin: 0 auto
<style>
*{
padding: 0;
margin: 0;
}
.father{
height: 100px;
width: 100px;
background-color: skyblue;
}
.son{
height: 50px;
width: 50px;
background-color: pink;
margin: auto;
}
</style>
<div class="father">
<div class="son"></div>
</div>
不独占一行的元素水平居中
- 给父元素设置
- text-align: center
<style>
*{
padding: 0;
margin: 0;
}
.marginBox{
height: 100px;
width: 100px;
background-color: skyblue;
text-align: center;
}
span{
background-color: pink;
}
</style>
<div class="father">
<div class="son"></div>
</div>
<div class="marginBox">
<span>12312</span>
<img src="" alt="">
</div>
margin语法
- 数值
- 负值
- auto(特殊取值)
- 百分比 参考父元素的宽度
padding
- 数值
- 百分比 参考父元素的宽度
总结+复习
- 元素类型的转换(一)
- 块级元素
- 行内元素\内联元素(其中包括特殊的行内块元素)
- 元素类型的转换(二)
- 块级元素
- 行内元素、内联元素
- 行内块元素\内联块元素
- 块元素div ph1-h6 ul ol li dl dt dd form hr
- 独占一行, 在文档流从上往下排列
- 设置宽高有效
- 默认宽高为父元素的100%, 默认宽高靠内容撑开
- 盒子模型的属性均有效
- 在网页中以块的形式存在, 作为容器, 用于布局
- 行内元素spansdel strong a u sub sup b em i br
- 不独占一行, 与其他行内元素或者行内块元素共用一行从左往右排列, 一行放不下主动换行
- 设置宽高无效
- 默认宽高靠内容撑开
- 盒子模型中padding, border, margin上下属性无效
- span常用于一行文具有不同样式的时候
- 紧紧包裹文字, 不会有多余空间: 左右的行内元素之间有间隙
- 行内块元素img input
- 不独占一行, 与其他的行内元素或者行内块元素共用一行从左往右排列,一行放不下主动换行
- 设置宽高有效
- 默认宽高不同浏览器设置不同, 后期需要我们自己设置
- 盒子模型的属性均有效
- 会出现幽灵空白节点