div嵌套div水平垂直居中能够使用position定位来实现,这是最经常使用的方法。css
<!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这四个属性。html
一般单独使用left、right、top、bottom均无效,须要在使用绝对定位position样式才能生效。htm
通常left和right在一个样式是只能使用其一,不能left和right都设置,要么使用left就不使用right,要么使用right就不使用left,若是left和right均使用将会出现兼容问题,一个对象设置了靠左left多少距离,天然右边距离天然就有了因此无需设置左边。对象
相同道理,top和bottom对一个对象只能使用其一,否则会出现逻辑兼容问题。譬如一我的让你往左走,一我的让你往右走,同时发出往左往右走这个时候你也很差判断往那边走。blog