盒子模型详解
在前端开发中,理解盒子模型是非常重要的。盒子模型主要包括内容区、填充区、边框区和外边距。本文将详细介绍盒子模型的各个方面及其常见样式设置。
1. 块级盒子
块级盒子特点:
独占一行。
对宽度和高度支持。
常见标签:div, ul, li, h1 ~ h6。
使用 display: block;。
2. 内联级盒子
内联级盒子特点:
不独占一行。
对宽度和高度不支持。
常见标签:span, a。
使用 display: inline;。
3. 内联块级盒子
内联块级盒子特点:
不独占一行。
对宽度和高度支持。
常见标签:img, input。
使用 display: inline-block;。
4. 弹性盒子
弹性盒子特点:
无论父级元素能否放下子元素,子元素始终横向布局。
使用 display: flex;。
内容区
width: 200px;
height: 100px;
box-sizing: content-box; 默认宽高针对内容区设置。
box-sizing: border-box; 宽高针对整个盒子设置。
填充区
从上开始,顺时针进行旋转,不够了找对称。
示例:
padding: 5px;
padding: 50px 20px;
padding: 50px 20px 10px;
padding: 50px 20px 10px 100px;
结合上下左右单独对某一个方向进行设置:
padding-top: 50px;
padding-bottom: 10px;
padding-left: 100px;
padding-right: 30px;
边框区
复合属性:
border-style: solid;/*边框样式*/
border-color: blue;/*边框颜色*/
border-width: 10px;/*边框宽度*/
border: solid 10px blue;
结合上下左右四个方向单独设置:
border-top: solid 10px blue;
border-bottom: dashed 10px pink;
border-left: dotted 10px red;
border-right: double 10px green;
外边距
从上开始,顺时针进行旋转,不够了找对称。
示例:
margin: 50px;
margin: 50px 20px;
margin: 50px 20px 100px;
margin: 50px 20px 100px 0;
结合上下左右四个方向单独设置:
margin-top: 50px;
margin-left: 100px;
margin-bottom: 10px;
margin-right: 30px;
auto; 水平方向居中,用于块级元素。
常见样式
1.保持图片不变形:
object-fit: cover;
2.阴影:
box-shadow: 水平 垂直 模糊度 颜色;
3.圆角边框:
border-radius: 10px;
4.列表样式去掉:
list-style: none;
背景相关样式
1.设置背景颜色:
background-color: gold;
2.设置背景图片:
background-image: url('path/to/image.jpg');
3.背景图片是否平铺:
background-repeat: no-repeat;
background-repeat: repeat;
background-repeat: repeat-x;
background-repeat: repeat-y;
4.设置背景图片大小:
background-size: cover;
5.设置背景图片位置:
background-position: center;
6.设置背景图片固定:
background-attachment: fixed;
字体相关样式
1.字体颜色:
color: red;
2.字体复合属性:
font-size: 16px;
font-weight: bold;
font-style: italic;
3.文字修饰线:
text-decoration: none;
text-decoration: underline;
text-decoration: line-through;
text-decoration: overline;
4.文本水平对齐方式:
text-align: right;
text-align: left;
text-align: center;
5.设置行高:
line-height: 1.5;
颜色表示方式
1.用颜色名表示:
color: red;
2.六位十六进制表示:
color: #ff0000;
3.RGB 表示:
color: rgb(255, 0, 0);
4.RGBA 表示:
color: rgba(255, 0, 0, 0.5);
5.透明度:
opacity: 0.5;
6.颜色渐变:
background: linear-gradient(to right, red, yellow);
7.透明色:
color: transparent;
定位
定位模式:
position: static;
position: fixed;
position: relative;
position: absolute;
结合模式:
/* 父级使用 relative */
.parent {
position: relative;
}
/* 子集元素使用 absolute */
.child {
position: absolute;
top: 10px;
left: 20px;
}