一、规则
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; 700px; font-size: 30px; color: #fff; height: 80px; padding-left: 20px; } .right { background: green; height: 40px; 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; 700px; font-size: 30px; color: #fff; height: 80px; padding-left: 20px; } .right { background: green; height: 40px; 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>
改为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去掉后就可以垂直居中了