首页 > 解决方案 > 绝对div父级内的css div子级

问题描述

对css有点新手问题。

我有一个居中的 div 父级(屏幕中心),position:absolute
现在我想在父级 div 中创建子级 div。他们应该有:

很像不同大小的列。

到目前为止我所做的(仅限父 div,因为我尝试过的一切都真的搞砸了:():

.parent {
  position: absolute;
  width: 80%;
  height: 75%;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  background: #000000;
  }
<div class="parent">
</div>

标签: htmlcss

解决方案


一个建议。不要position:absolute用于布局。仅在必要时。排列元素的方法有很多,而不仅仅是位置:绝对。

不太确定你“搞砸了什么”,但你可以使用 flexbox -> add display:flexon parent 并根据需要在其中安排你的子 div

在此处阅读有关flexbox和其他教程的更多信息

.parent {
  position: absolute;
  width: 80%;
  height: 75%;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  background: #000000;
  display: flex;
  flex-wrap: wrap;
}

.child {

  box-sizing: border-box;
}

.child1 {
  background: red;
  flex: 0 0 30%;
  padding: 15px;
}

.child2 {
  background: green;
  flex: 0 0 50%;
}

.child3 {
  background: blue;
  flex-grow: 1;
}
<div class="parent">
 <div class="child child1">text with padding</div>
 <div class="child child2">no padding</div>
 <div class="child child3">no padding</div>
</div>


推荐阅读