1、水平居中
水平居中在现代浏览器中的实现非常简单,只要使用 margin:0 auto; 即可轻松实现,但是在早期浏览器(IE6等)中,需要使用在父元素中使用text-align:center;属性,然后在需要居中的元素中使用text-align:left;即可;
这是因为在Internet Explorer中text-align属性是可继承的,所以我们需要恢复为我们习惯的左对齐浏览习惯。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<!DOCTYPE html> <head> <title> CSS+Div实现水平居中对齐的页面布局 </title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <style type="text/css"> body { text-align:center; } div#wrap { text-align:left; width:760px; margin:0 auto; border:1px solid #333; background-color:#ccc; } </style> </head> <body> <div id="wrap"> 在Firefox等现代浏览器设定页面元素的水平居中,只要指定margin:0 auto;即可 <pre> div#wrap { width:760px; margin:0 auto; /*这里的0可以任意值*/ border:1px solid #ccc; background-color:#999; } 在Internet Explorer 6 及以下的版本中我们还要做以下的设置: body { text-align:center; } div#wrap { text-align:left; } </pre> </div> </body> </html> |
1 |
还有另外其他的水平居中方式,我认为不如上面的好,但是下面会讲到一样可以用于水平居中的垂直居中方式。 |
2、垂直居中
1 |
在当前要居中的元素的原父元素的position设置为:position:relative;,然后在居中元素外添加一个div元素style="position:absolute;left:50%;",居中元素的style="position:relative;left:-50%;"。最后加上hack就是: |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>垂直居中</title> <style> *{margin:0;padding:0;} body{font-family:consolas;padding:20px;} img, p{border:1px dotted #bbb;padding:5px;} p{margin-bottom:10px;} a{text-decoration:none;} .wrap{ width:500px;height:300px;border:3px solid #ddd;margin:0 auto;padding:20px;display:table; *position:relative; /* *是ie的hack */ } .hack{ display:table-cell;vertical-align:middle; /* 现代浏览器垂直居中实现 */ *position:absolute;*top:50%; /* *是ie的hack */ } .cnt{ *position:relative;*top:-50%; /* *是ie的hack */ } </style> </head> <body> <div class="wrap"> <div class="hack"> <div class="cnt"> <img src="https://img.alipay.com/images/cms2/201104/20110425930115.png" alt="google" /> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it. </p> </div> </div> </div> </body> </html> |
1 |
1 |