margin:外边距的意思。表示边框到最近盒子的距离。css
/*表示四个方向的外边距离为20px*/
margin: 20px;
/*表示盒子向下移动了30px*/
margin-top: 30px;
/*表示盒子向右移动了50px*/
margin-left: 50px;
/*表示盒子向上移动了100px*/
margin-bottom: 100px;
2.一、margin塌陷问题html
当时说到了盒模型,盒模型包含着margin,为何要在这里说margin呢?由于元素和元素在垂直方向上margin里面有坑。spa
咱们来看一个例子:code
html结构: <div class="father"> <div class="box1"></div> <div class="box2"></div> </div> css样式: *{ padding: 0; margin: 0; } .father{ width: 400px; overflow: hidden; border: 1px solid gray; } .box1{ width: 300px; height: 200px; background-color: red; margin-bottom: 20px;} .box2{ width: 400px; height: 300px; background-color: green; margin-top: 50px; }
当给两个标准流下兄弟盒子 设置垂直方向上的margin时,那么以较大的为准,那么咱们称这种现象叫塌陷。无法解决,咱们称为这种技巧叫“奇淫技巧”。htm
当咱们给两个标准流下的兄弟盒子设置浮动以后,就不会出现margin塌陷的问题。blog
2.二、margin:0 auto;io
div{
width: 780px;
height: 50px;
background-color: red;
/*水平居中盒子*/
margin: 0px auto;
/*水平居中文字*/
text-align: center;
}
当一个div元素设置margin:0 auto;时就会居中盒子,那咱们知道margin:0 auto;表示上下外边距离为0,左右为auto的距离,那么auto是什么意思呢?class
设置margin-left:auto;咱们发现盒子尽量大的右边有很大的距离,没有什么意义。当设置margin-right:auto;咱们发现盒子尽量大的左边有很大的距离。当两条语句并存的时候,咱们发现盒子尽量大的左右两边有很大的距离。此时咱们就发现盒子居中了。技巧
另外若是给盒子设置浮动,那么margin:0 auto失效。im
使用margin:0 auto;注意点:
另一定要知道margin属性是描述兄弟盒子的关系,而padding描述的是父子盒子的关系
2.三、善于使用父亲的padding,而不是margin
如何实现如图的效果。
咱们来看看这个案例,它的坑在哪里?
下面这个代码应该是你们都会去写的代码。
*{
padding: 0;
margin: 0;
}
.father{
width: 300px;
height: 300px;
background-color: blue;
}
.xiongda{
width: 100px;
height: 100px;
background-color: orange;
margin-top: 30px;
}
效果:
由于父亲没有border,那么儿子margin-top实际上踹的是“流” 踹的是行,因此父亲掉下来了,一旦给父亲一个border发现就行了。
.father{
width: 300px;
height: 300px;
background-color: blue;
border: 1px solid black;
}
.box1{
width: 100px;
height: 100px;
background-color: red;
margin-top: 100px;
}
那么问题来了,咱们不可能在页面中平白无故的去给盒子加一个border,因此此时的解决方案只有一种。就是使用父亲的padding。让子盒子挤下来。
.father{
width: 300px;
height: 300px;
background-color: blue;
padding-top: 100px;
}
.box1{
width: 100px;
height: 100px;
background-color: red;
}