css 按特定物料居中划分

xcitsw88  于 2023-01-27  发布在  其他
关注(0)|答案(2)|浏览(105)

是否可以不将整个子容器div居中,而是将特定项居中?第一个p和最后一个p的内容具有不同的高度,并且可以动态更改。

.container {
  display:flex;
  align-items: center;
  height: 300px;
  background-color: red;
}

.child-container {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  background-color: purple;
}

.big{
  line-height:40px;
}

.bigger{
  line-height:80px;
}
<div class="container">
<div class="child-container">
  <p class="big">Lorem ipsum</p>
  <p>Center this</p>
  <p class="bigger">Lorem ipsum</p>
</div>
</div>
6tdlim6h

6tdlim6h1#

给子容器一个相对位置,给中间段落一个绝对位置,然后给中间段落一个上下边距50vh:

.container {
  display:flex;
  align-items: center;
  height: 300px;
  background-color: red;

}

.child-container {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  background-color: purple;
    position: relative;
}

.big{
  line-height:40px;
}

.bigger{
  line-height:80px;
}

.center {
    position: absolute;
    margin-top: 50vh;
    margin-bottom: 50vh;
}
<div class="container">
<div class="child-container">
  <p class="big">Lorem ipsum</p>
  <p class="center">Center this</p>
  <p class="bigger">Lorem ipsum</p>
</div>
</div>
tkclm6bt

tkclm6bt2#

假设您的意思是水平居中,那么您只需要使用flex-grow扩展子容器,并对您选择的子容器使用align-self:

.container {
    display: flex;
    align-items: center;
    height: 300px;
    background-color: red;
  }

  .child-container {
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    background-color: purple;
    flex-grow: 1;
    align-items: flex-start;
  }

  .child-container * {
    background-color: greenyellow;
  }

  .big {
    line-height: 40px;
  }

  .bigger {
    line-height: 80px;
  }

  .center {
    align-self: center;
  }
<div class="container">
<div class="child-container">
  <p class="big">Lorem ipsum</p>
  <p class="center">Center this</p>
  <p class="bigger">Lorem ipsum</p>
</div>
</div>

相关问题