css – 为什么div会以相对/绝对定位崩溃?

前端之家收集整理的这篇文章主要介绍了css – 为什么div会以相对/绝对定位崩溃?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在使用浮动定位时处理了divs崩溃的内容(例如使用overflow:hidden解决),但我正在尝试学习绝对/相对定位,并且无法弄清楚为什么容器div会崩溃.我的测试用例:
  1. <html>
  2. <head>
  3. <style type="text/css">
  4. body {
  5. background-color:#eee;
  6. }
  7.  
  8. #content {
  9. margin:0 auto;
  10. position:relative;
  11. border:1px solid red;
  12. width:800px;
  13. display:block;
  14. background-color:white;
  15. }
  16.  
  17. #header {
  18. border:1px solid black;
  19. background-color:#777;
  20. color:white;
  21. width:800px;
  22. position:absolute;
  23. left:0;
  24. top:0;
  25. }
  26.  
  27. #leftcol {
  28. position:absolute;
  29. border:1px solid black;
  30. background-color:#ddd;
  31. width:200px;
  32. top:100px;
  33. left:0;
  34. }
  35.  
  36. #rightcol {
  37. position:absolute;
  38. top:100px;
  39. left:205px;
  40. border:1px solid black;
  41. background-color:#ddd;
  42. width:500px;
  43. }
  44.  
  45. </style>
  46. <title>CSS Positioning Example 1</title>
  47. </head>
  48.  
  49. <body>
  50. <div id="content">
  51.  
  52. <div id="header">
  53. <h1>The Awesome Website</h1>
  54. </div>
  55.  
  56. <div id="leftcol">
  57. <h2>About</h2>
  58. <p>
  59. This website is so awesome because it was made by someone
  60. and that is really all there is to it. There.
  61. </p>
  62. </div>
  63.  
  64. <div id="rightcol">
  65. <p>This is where I'm going to put some real body text so that it goes
  66. on and on for a while and so I can get a sense of what happens when
  67. the text in the paragraph keeps going and the Box containing it keeps
  68. going on as well.
  69. </p>
  70. </div>
  71.  
  72. </div>
  73.  
  74. </body>
  75. </html>

这里发生了什么?为什么红边内容div会崩溃,即使它包含其他div?

解决方法

这是因为它的所有内容都被定位为position:absolute.这使得这些元素不再流动,并且(布局方面)就像它们甚至不存在一样.考虑使用position:relative来定位内容.

猜你在找的CSS相关文章