css margin疊加問題

來源:互聯網
上載者:User

w3c認為margin疊加是合理的。不管是不是bug,但是這個問題真的存在。看下面這個例子:

 
  1. < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  2. <html xmlns="http://www.w3.org/1999/xhtml"> 
  3. <head> 
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
  5. </head><head> 
  6. <style type="text/css"> 
  7. *{padding:0;margin:0;}  
  8. .box{background:#ccc; }  
  9. .content{background:#eee;margin: 20px auto;}  
  10. .an-box{ margin:50px auto;background:#999999;}  
  11. </style> 
  12. </head> 
  13. <body> 
  14. <div class="box"> 
  15. <div class="content">margin: 20px auto</div> 
  16. <div class="content">margin: 20px auto</div> 
  17. </div> 
  18. <div class="box"> 
  19. <div class="content">margin: 20px auto</div> 
  20. </div> 
  21. <div class="box"> 
  22. <div class="content">margin: 20px auto</div> 
  23. </div> 
  24. <div class="an-box">margin: 50px auto</div> 
  25. </body> 
  26. </html> 

解決這個問題的方法有不少,先來看看這個,在外層的容器中加:overflow:hidden;zoom:1;

 

 
  1. < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  2. <html xmlns="http://www.w3.org/1999/xhtml"> 
  3. <head> 
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
  5. </head><head> 
  6. <style type="text/css"> 
  7. *{padding:0;margin:0;}  
  8. .box{background:#ccc; overflow:hidden;zoom:1 }  
  9. .content{background:#eee;margin: 20px auto; }  
  10. .an-box{ margin:50px auto;background:#999999;}  
  11. </style> 
  12. </head> 
  13. <body> 
  14. <div class="box"> 
  15. <div class="content">這裡兩個還是存在疊加margin: 20px auto</div> 
  16. <div class="content">這裡兩個還是存在疊加margin: 20px auto</div> 
  17. </div> 
  18. <div class="box"> 
  19. <div class="content">margin: 20px auto</div> 
  20. </div> 
  21. <div class="box"> 
  22. <div class="content">margin: 20px auto</div> 
  23. </div> 
  24. <div class="an-box">margin: 50px auto</div> 
  25. </body> 
  26. </html> 

還有外層的容器中加邊框屬性,在疊加元素加空塊狀元素等等。。還有就是用padding來取代margin

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.