具有负值和高度的CSS相对定位

前端之家收集整理的这篇文章主要介绍了具有负值和高度的CSS相对定位前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图负面定位一个DIV元素(在例子中是#content),但我的问题是div的容器(#wrapper2),得到太多的高度(实际上是#content给出的高度,但就像我’移动内容,我想相应地减少#wrapper2的高度.

在这里,我举一个例子来展示我想要实现的目标.如果您尝试该样本,您将看到该页脚距离容器太远.我可以在这里做一个肮脏的黑客并使页脚顶部:-200px但是然后窗口的滚动条越过页脚.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Relative positioning demo</title>
  5. <style>
  6. /* RESET STUFF */
  7. html {
  8. margin:0;
  9. padding:0;
  10. border:0;
  11. }
  12.  
  13. body,div,p,h1 {
  14. margin: 0;
  15. padding: 0;
  16. border: 0;
  17. }
  18. /* END RESET */
  19.  
  20. h1 {
  21. background-color: yellow;
  22. }
  23.  
  24. p {
  25. margin-bottom: 1em;
  26. }
  27.  
  28. /* LAYOUT */
  29. #wrapper1 {
  30. text-align: center;
  31. height: 250px;
  32. background-color: lightgray;
  33. }
  34. #wrapper2 {
  35. background-color: lightblue;
  36. }
  37. #content {
  38. width: 950px;
  39. margin: 0 auto;
  40. background-color: white;
  41. padding: 5px;
  42. height: 560px;
  43.  
  44. /* HERE's my problem */
  45. position: relative;
  46. top: -200px;
  47. }
  48. #footer {
  49. background-color: black;
  50. color: white;
  51. height: 40px;
  52. line-height: 40px;
  53. text-align: center;
  54. }
  55. </style>
  56. </head>
  57. <body>
  58. <div id="wrapper1">
  59. <h1>This is my heading</h1>
  60. </div>
  61. <div id="wrapper2">
  62. <div id="content">
  63. My content here
  64. </div>
  65. </div>
  66. <div id="footer">
  67. lorem ipsum
  68. </div>
  69. </body>
  70. </html>

如果您有任何建议,请记住,我必须同时看到两个,浅灰色和浅蓝色背景(它们是我网站上的图像),所以margin-top:-200px不是一个选项(就像我在相关问题中建议的那样) ‘搜索过)

谢谢!

解决方法

将top属性更改为margin-top

Demo

  1. position: relative;
  2. top: -200px;

变成

  1. margin-top: -200px;

猜你在找的CSS相关文章