w3c認為margin疊加是合理的。不管是不是bug,但是這個問題真的存在。看下面這個例子:
- < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- </head><head>
- <style type="text/css">
- *{padding:0;margin:0;}
- .box{background:#ccc; }
- .content{background:#eee;margin: 20px auto;}
- .an-box{ margin:50px auto;background:#999999;}
- </style>
- </head>
- <body>
- <div class="box">
- <div class="content">margin: 20px auto</div>
- <div class="content">margin: 20px auto</div>
- </div>
- <div class="box">
- <div class="content">margin: 20px auto</div>
- </div>
- <div class="box">
- <div class="content">margin: 20px auto</div>
- </div>
- <div class="an-box">margin: 50px auto</div>
- </body>
- </html>
解決這個問題的方法有不少,先來看看這個,在外層的容器中加:overflow:hidden;zoom:1;
- < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- </head><head>
- <style type="text/css">
- *{padding:0;margin:0;}
- .box{background:#ccc; overflow:hidden;zoom:1 }
- .content{background:#eee;margin: 20px auto; }
- .an-box{ margin:50px auto;background:#999999;}
- </style>
- </head>
- <body>
- <div class="box">
- <div class="content">這裡兩個還是存在疊加margin: 20px auto</div>
- <div class="content">這裡兩個還是存在疊加margin: 20px auto</div>
- </div>
- <div class="box">
- <div class="content">margin: 20px auto</div>
- </div>
- <div class="box">
- <div class="content">margin: 20px auto</div>
- </div>
- <div class="an-box">margin: 50px auto</div>
- </body>
- </html>
還有外層的容器中加邊框屬性,在疊加元素加空塊狀元素等等。。還有就是用padding來取代margin