首页 > 解决方案 > 我将如何使用绝对和相对标签来定位 CSS div

问题描述

我想让某些 div 的默认垂直位置是相对的:这样它们就在顶部元素的正下方。但我希望能够定义它们的水平位置。例如,left: 30px 但 top 可以是可变的。我将如何做到这一点?

标签: htmlcsscss-position

解决方案


尝试这个:

body {
  margin: 0;
  overflow-x: hidden; /*to avoid overflow because of 'left:30px' given to wrapper2*/
}
.wrapper1 {
  height: 50px;
  background: #000;
}
.wrapper2 {
  position: absolute;
  width: 100%;
  left: 30px;
}
.child1 {
  background: red;
  height: 30px;
}
.child2 {
  background: blue;
  height: 30px;
}
<div class="wrapper1"></div>
<div class="wrapper2">
  <div class="child1"></div>
  <div class="child2"></div>
</div>

为了增加两者之间的相对距离wrappers,您可以使用margin-topbottom

希望能帮助到你!


推荐阅读