1. 程式人生 > >前端知識點之magin的用法與注意事項

前端知識點之magin的用法與注意事項

margin:

margin的定義和用法:

margin是一個設定所有外邊距的屬性;

注意 :塊級元素的垂直相鄰外邊距會合並,而行內元素實際上不佔上下外邊距。

行內元素的的左右外邊距不會合並。同樣地,浮動元素的外邊距也不會合並。

允許指定負的外邊距值,不過使用時要小心。


使用margin時的注意事項 :

消除子盒子的margin-top對父級盒子的影響的方法:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>blockAndInline</title>
</head>
<style>
    body{
        margin:0px;
    }
    .box-test-1{
        background:red;
        width:100px;
        height:100px;
    }
    .box-test-2{
        background:blue;
        width:50px;
        height:50px;
        margin-top:20px;
    }
</style>
<body>
    <div class="box-test-1">
        <div class="box-test-2"></div>
    </div>
</body>
</html>

 瀏覽器顯示的結果

1:可以利用父級盒子的padding-top來代替子盒子的margin-top的值;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>blockAndInline</title>
</head>
<style>
    body{
        margin:0px;
    }
    .box-test-1{
        background:red;
        width:100px;
        height:100px;
        padding-top:20px;
    }
    .box-test-2{
        background:blue;
        width:50px;
        height:50px;
        margin-top:20px;
    }
</style>
<body>
    <div class="box-test-1">
        <div class="box-test-2"></div>
    </div>
</body>
</html>


2:給父級元素加上:overflow:hidden;
3:在父盒子的外部加上邊框也可以消除margin-top對父盒子的影響;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>blockAndInline</title>
</head>
<style>
    body{
        margin:0px;
    }
    .box-test-1{
        background:red;
        width:100px;
        height:100px;
        border:1px solid #000;
    }
    .box-test-2{
        background:blue;
        width:50px;
        height:50px;
        margin-top:20px;
    }
</style>
<body>
    <div class="box-test-1">
        <div class="box-test-2"></div>
    </div>
</body>
</html>