一、規則
1. 某div不設置寬度,那么width默認為auto.
2. 某子元素div的width為100%(或者設置為等於父元素寬度的具體值,比如父元素width為100px,子元素width也設置為100px),則此子元素的寬度 = 父元素width值(不包括父元素邊框,內邊距)+子元素的邊框、內邊距寬度
4. 某個div的width不設置,或者設置為auto, 子元素的寬度會包含在父元素內,子元素邊框、內邊距都在不會疊加到子元素的長度上
二、實例
<!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>Document</title>
<style>
.main {
background: red;
height: 40px;
width: 700px;
font-size: 30px;
color: #fff;
height: 80px;
padding-left: 20px;
}
.right {
background: green;
height: 40px;
width: auto;
padding-left: 40px;
}
</style>
</head>
<body>
<div class="main">
<div class="right">right</div>
</div>
</body>
</html>
效果圖:

<!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>Document</title>
<style>
.main {
background: red;
height: 40px;
width: 700px;
font-size: 30px;
color: #fff;
height: 80px;
padding-left: 20px;
}
.right {
background: green;
height: 40px;
width: 100%;
padding-left: 40px;
}
</style>
</head>
<body>
<div class="main">
<div class="right">right</div>
</div>
</body>
</html>
效果圖:

如果right再加一個padding-right:40px,green區域要再加長40px
三、高度的設置類似於寬度,我們結合flexbox彈性布局看下效果:
<!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>Document</title>
</head>
<style>
.flex-container {
display: flex;
flex-direction: row;
justify-content: flex-start;
height: 200px;
}
/* 以下為輔助樣式 */
.flex-container {
background-color: #F0f0f0;
}
.flex-container .flex-item {
padding: 20px;
height: 200px;
background-color: #B1FF84;
}
.flex-container .flex-item:first-child {
background-color: #F5DE25;
}
.flex-container .flex-item:last-child {
background-color: #90D9F7;
}
</style>
<body>
<div class="flex-container">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
</div>
</body>
</html>

改為width:auto

想讓文字垂直居中,設置line-height
<!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>Document</title>
</head>
<style>
.flex-container {
display: flex;
flex-direction: row;
justify-content: flex-start;
height: 200px;
line-height: 200px;
}
/* 以下為輔助樣式 */
.flex-container {
background-color: #F0f0f0;
}
.flex-container .flex-item {
padding: 20px;
height: auto;
background-color: #B1FF84;
}
.flex-container .flex-item:first-child {
background-color: #F5DE25;
}
.flex-container .flex-item:last-child {
background-color: #90D9F7;
}
</style>
<body>
<div class="flex-container">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
</div>
</body>
</html>

發現並未居中,因為line-height的leading加在padding-top下面,所以居中位置會往下偏移20px
把上下的padding去掉后就可以垂直居中了
