08-認識margin

一、margin

margin:外邊距的意思。表示邊框到最近盒子的距離。css

/*表示四個方向的外邊距離爲20px*/
margin: 20px;
/*表示盒子向下移動了30px*/
margin-top: 30px;
/*表示盒子向右移動了50px*/
margin-left: 50px;
/*表示盒子向上移動了100px*/
margin-bottom: 100px;

二、margin的用法

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;注意點:

  1. 使用margin: 0 auto;水平居中盒子必須有width,要有明確width,文字水平居中使用text-align: center;
  2. 只有標準流下的盒子才能使用margin:0 auto;
  3. 當一個盒子浮動了,固定定位,絕對定位,margin:0 auto; 不能用了
  4. margin:0 auto;居中盒子。而不是居中文本,文字水平居中使用text-align: center;

另一定要知道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;
}
相關文章
相關標籤/搜索