1.盒模型常用属性
- 例如以下元素的属性:
content,padding,border,margin,width,height,auto
padding-top,padding-right,padding-bottom,padding-left
margin-top,margin-right,margin-bottom,margin-left
border-top,border-bottom,border-right,border-left - 如下图:
- 200*200是中心内容区:content
- padding:10px
- border:2px
- margin:30px
- width:200px
- height:200px
- margin: auto:水平垂直居
- pading和margin:背景透明,只能设置宽度
- border:可设置宽度,样式,颜色。比如:给2相素边框和灰黑色:border: 2px solid #000;
2.盒模型元素大小计算,box-sizing的用法
- box-sizing重新计算盒大小的用法,如下图:
- 样式初始化,代码如下:
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
</style>
content-box: 默认值,以内容区为准
box-sizing: content-box;
box-sizing: border-box;
长:108+402+62=200px
宽:88+402+62=180px
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>用户自定义元素大小的计算方式</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.box {
width: 200px;
height: 180px;
border: 6px solid #000;
padding: 40px;
background-color: violet;
background-clip: content-box;
box-sizing: content-box;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
3.盒模型水平垂直居中
- 两个盒子,使里面的小盒子在大盒子里水平垂直居中,如下图:
- 弹性盒子居中flex能够快速搞定,今使用margin: auto来实现水平垂直居中,演示代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>块元素的垂直居中margin:auto</title>
<style>
.container {
width: 300px;
height: 300px;
background-color: deepskyblue;
/* 弹性盒子居中flex */
/* display: flex;
justify-content: center;
align-items: center; */
position: relative;
}
.container .item {
width: 100px;
height: 100px;
background-color: firebrick;
position: absolute;
/* 让当前元素绝对定位的充满整个低级容器 */
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="container">
<div class="item"></div>
</div>
</body>
</html>