說明
- 源代碼
- 學習
盒子模型(css重點)
css學習三大重點: css盒子模型、 浮動、 定位
- 目標:
- 能說出盒子模型由哪四部分組成: 內容、邊框、內外邊距
- 能說出內邊距的作用,設置不同數值分別代表的意思: 控制內部塊級元素和寬框的距離
- 能說出塊級盒子居中對齊需要的2個條件
- 能說出外邊距合并的解決辦法
- 應用:
- 能利用邊框復合寫法給元素添加邊框
- 能計算盒子的實際大小
- 能利用盒子模型布局模塊案例
1. 看透網頁布局的本質
- 看透網頁布局的本質:
- 首先利用CSS設置好盒子的大小,然后擺放盒子的位置
- 最后把網頁元素(文字、圖片等)放入盒子里面
2. 盒子模型(Box Model)
- 所謂盒子模型:
- 就是把HTML頁面中的布局元素看作是一個矩形的盒子,也就是一個盛裝內容的容器.
3. 盒子邊框 (border)
3.1 邊框重疊
- 兩個單元格之間的邊框會出現重疊,從而使邊框變粗
table{border-collapse: collapse;
}
- collapse 單詞是合并的意思
- 以上屬性表示相鄰的邊框合并在一起
table{border-collapse: collapse;
}
4. 內邊距 (padding)
- 內容與邊框的距離
- 會改變盒子的大小
div{width: 200px;height: 200px;border: 1px solid red;padding: 10px 20px;
}
- 此時的盒子高度是220px,寬度是220px
- padding的值按順時針安利
4.1 要求盒子的左邊內邊距是5像素
padding-left: 5px;
4.2 要求簡寫的形式寫出一個盒子上下是25像素,左右是15像素
padding: 25px 15px;
4.3 簡寫的形式寫出一個盒子上內邊距是12像素下內邊距是0左內邊距是25右內邊距是10
paddding: 12px 10px 0 25px
4.4 字數不一樣的導航欄制作解決方案
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><title>Document</title><style>.nav {width: 100%;height: 41px;border-top: 3px solid #ff8500;border-bottom: 1px solid #ebeef0;background-color: #fcfcfc;}.nav a {text-decoration: none;color: black;display: inline-block;padding: 0 15px;height: 41px;line-height: 41px;font-size: 16px;}.nav a:hover {background-color: rgba(0, 0, 0, 0.2);}</style></head><body><div class="nav"><a href="#">一</a><a href="#">兩字</a><a href="#">三個字</a><a href="#">我是四字</a><a href="#">我有五個字</a><a href="#">我只有六個字</a></div></body>
</html>
- 盒子的實際大小 = 內容寬度 + 內邊距 + 邊框
4.5 padding值不撐開盒子
- 如果盒子沒有指定寬度或者高度,那么padding值不會撐開寬度或高度
<style>div{width: 100px;height: 100px;background-color: pink;}div p{height: 30px;background-color: purple;padding: 15px;}
</style>
<body><div><p>我不會撐開p盒子的寬高 </p></div>
</body>
5. 外邊距 (margin)
- 盒子與盒子之間的距離
5.1 塊級盒子水平居中對齊
- 一般用于最外層的盒子,讓頁面的大部分信息始終在屏幕中心.
<style>div{width: 600px;height: 600px;margin: 0 auto;background-color:pink;}
</style>
<body><div></div>
</body>
5.2 常見的行內塊
- img
- input
- 單元格
5.3 行內元素和塊級元素的居中對齊
text-align
:可以讓行內元素,行內塊元素水平對齊margin: 0 auto
:可以讓塊級盒子水平居中
<style>div{width: 600px;height: 300px;background-color: pink;margin: 0 auto;text-align: center;}
</style>
<body><div>穩住<strong>我們能贏</strong><input type="text"></div>
</body>
5.4 插入圖片和背景圖的位置移動
插入圖片
: 通常用于產品展示,移動位置靠盒模型(padding margin)背景圖片
: 一般是小圖標背景或超大背景圖, 移動位置只能靠background-position
img {width: 200px;height: 210px;margin: 5px;
}
div {width: 400px;height: 400px;background: url(...) no-repeat;/* x方向移動30像素 y方向移動50像素 */background-position: 30px 50px;
}
5.5 外邊距的合并
- 1)垂直外邊距合并(左右并不會出現)
.top{margin-bottom: 100px;
}
.bottom{margin-top: 50px;
}
<div class="top">
<div class="bottom">
此時,上面的盒子和下面的盒子距離為: 50px, 即上下外邊距會取較大值
- 2)兩個嵌套的塊級盒子模型
<div class="container"><p class="inner"></p>
</div>
如果給父元添加上內邊距會是整個容器的高度變大
如果使用子元素的上外邊距.會使父元素和子元素全部向下移動對應的距離
正確做法如下:
.container{width: 500px;height: 500px;background-color: marron;border-top: 1px solid transparent;
}
.inner {width: 50px;height: 50px;background-color: skyblue;margin-top: 50px;
}
補充: 盒子陰影的參數(CSS3)
box-shadow: x y 陰影虛實 陰影尺寸 陰影顏色 內/外陰影