div嵌套div水平垂直居中可以使用position定位来实现,这是最常用的方法。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> .div1 { width:800px; height:500px; border:2px solid #000; position:relative; } .div2 { width:200px; height:200px; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; background-color: red; } </style> </head> <body> <div class="div1"> <div class="div2"></div> </div> </body> </html>
需要注意的是 left right top bottom这四个属性。
通常单独使用left、right、top、bottom均无效,需要在使用绝对定位position样式才能生效。
一般left和right在一个样式是只能使用其一,不能left和right都设置,要么使用left就不使用right,要么使用right就不使用left,如果left和right均使用将会出现兼容问题,一个对象设置了靠左left多少距离,自然右边距离自然就有了所以无需设置左边。
相同道理,top和bottom对一个对象只能使用其一,不然会出现逻辑兼容问题。譬如一个人让你往左走,一个人让你往右走,同时发出往左往右走这个时候你也不好判断往那边走。