3.CSS盒子模型 border、margin、padding

盒子模型有兩種,分別是 ie 盒子模型和標(biāo)準(zhǔn) w3c 盒子模型

border 邊框

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        #cube {
            width: 300px;
            height: 300px;
            background: gray;
            border:20px solid blue;
        }
    </style>
</head>
<body>
    <div id="cube"></div>
</body>
</html>

如下代碼代表20像素藍(lán)色的實(shí)線(solid)邊框

border:20px solid blue;
image.png

虛線(dashed)邊框

border:20px dashed blue;
image.png

3D凹邊(inset)

border:20px inset blue;
image.png

還有很多值,沒有必要一一背下來,用時(shí)去查就可以了

我們也可以分別設(shè)置各方向邊框的效果


image.png

margin 外邊距

我們使用一個(gè)div包裹三個(gè)同樣寬高向左浮動(dòng)的div

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        #content {
            width: 1000px;
            height: 500px;
            border:1px solid red;
        }
        #text1 {
            width: 400px;
            height: 200px;
            border: 1px solid green;
            float: left;
        }
        #text2 {
            width: 400px;
            height: 200px;
            border: 1px solid blue;
            float: left;
        }
        #text3 {
            width: 400px;
            height: 200px;
            border: 1px solid orange;
            float: left;
        }
        
    </style>
</head>
<body>
    <div id="content">
        <div id="text1"></div>
        <div id="text2"></div>
        <div id="text3"></div>
    </div>
</body>
</html>
image.png

我們發(fā)現(xiàn)內(nèi)部的div會(huì)并列布局,第三個(gè)div因?yàn)樗挾刃∮谧约旱膶挾?,所以被擠至下面

我們?yōu)閮?nèi)部第一個(gè)div增加margin屬性

margin: 10px;

效果如下:


image.png

margin可以同時(shí)設(shè)置4個(gè)方向的值,從上邊開始,順時(shí)針方向取值。
如下代表 上方margin10px,右方margin20px,下方margin30px,左方margin40px

margin: 10px 20px 30px 40px;

也可以不寫全四個(gè)方向的值,沒有值的方向就取對(duì)邊方向的值
如下代表 上方margin10px,右方margin20px,下方margin30px,左方margin20px

margin: 10px 20px 30px;

如果只設(shè)置某個(gè)方向的margin,可以使用如下屬性


image.png

例如,margin左邊20px:

margin-left: 20px;

利用margin實(shí)現(xiàn)在父容器水平居中(和左右浮動(dòng)一起使用無效):

margin: 0px auto;

padding 內(nèi)邊距

使用方式和margin類似,背景色會(huì)填充在padding的范圍內(nèi)。也可以增加一條背景色的屬性,讓背景色只填充在內(nèi)容區(qū)域

background-clip:content-box;
image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容