设置 box-sizing:border-box(原本的默认值为:content-box)
box-sizing: content-box;/*盒子宽度=CSS中设置的width+border+padding*/ box-sizing: border-box;/*盒子的宽度=css中设置的width*/
实例对比
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .box1{ box-sizing: content-box;/*盒子宽度=CSS中设置的width+border+padding*/ width:300px; height:200px; padding:10px; margin: 10px; color:red; border:5px solid blue; } .box2{ box-sizing: border-box;/*盒子的宽度=css中设置的width*/ width:300px; height:200px; padding:10px; margin: 10px; color:red; border:5px solid blue; } </style> </head> <body> <div class="box1"> <p>box-sizing: content-box;/*盒子宽度=CSS中设置的width+border+padding*/</p> </div> <div class="box2"> <p>box-sizing: border-box;/*盒子的宽度=css中设置的width*/</p> </div> </body> </html>
可以看到,第一个div被pading等因素撑大