首页 > 解决方案 > div 边距和绝对位置

问题描述

看这个例子 = https://codepen.io/anon/pen/zaXMXo

* {
  box-sizing: border-box;
}
html, body {
  height: 100%
}
.wrapper {
  background: red;
  min-height: 100%;
}
.left {
  position: absolute;
  width: 200px;
  top: 0;
  bottom: 0;
  background: yellow;
}
.content {
  background: blue;
  margin-left: 230px;
  margin-top: 30px;
  width: 300px;
}
<div class="wrapper">
  <div class="left"></div>
  <div class="content">
            hello content <br />
            hello content <br />
            hello content <br />
            ...
   </div>
 </div>

有人可以告诉我:

1)为什么黄色块不在全高?

2)为什么蓝色块margin-top在顶部添加空白?

如何修复它?

标签: htmlcssflexbox

解决方案


1)为什么黄色块不在全高?

是的,这只是由于第二个问题,它看起来不是。

2)为什么蓝色块margin-top在顶部添加空白?

这是由于折叠边距,因为包装容器没有任何顶部边距或填充(也没有边框顶部),因此它与.content子元素的顶部边距合并。您可以设置padding-top, 或border-topon.wrapper来缓解这种情况。

* {
  box-sizing: border-box;
}

html,
body {
  padding: 0; /* always good to clean padding and margin on html/body */
  margin: 0;
  height: 100%
}

.wrapper {
  background: red;
  min-height: 100%;
  border-top: 1px green solid; /* border fixes margin collapsing */
}

.left {
  position: absolute;
  width: 200px;
  top: 0;
  bottom: 0;
  background: yellow;
}

.content {
  background: blue;
  margin-left: 230px;
  margin-top: 30px;
  width: 300px;
}
<div class="wrapper">
  <div class="left"></div>
  <div class="content">
            hello content <br />
            hello content <br />
            hello content <br />
            ...
   </div>
 </div>


推荐阅读