默认情况下设置盒子的width是指内容区域,所以在设置边框会使得盒子往外扩张,如果要让css设置的width就是盒子最终的宽度,那么就要设置box-sizing:border-box,
这样添加border后,盒子会往内扩张,也就是设置的width就是盒子最终大小,box-sizing: content-box 是它的默认值
1.默认情况
<!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> div{ background-color: aqua; width: 500px; height: 500px; border: 10px solid gold; padding: 20px; box-sizing: content-box; margin: 0 auto; } </style> <body> <div>pppp</div> </body> </html>
效果如下:
2.box-sizing:border-box
<!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> div{ background-color: aqua; width: 500px; height: 500px; border: 10px solid gold; padding: 20px; box-sizing: border-box; margin: 0 auto; } </style> <body> <div>pppp</div> </body> </html>
效果如下: