css 使用弹性框将一个元素居中对齐,同时将其唯一的同级元素右对齐

e0uiprwp  于 2023-03-05  发布在  其他
关注(0)|答案(4)|浏览(209)

我尝试使用Flexbox实现这一点:

我知道如何通过使用隐藏元素as in this fiddle来实现:

.container {
  display: flex;
  justify-content: space-between;
  border: 3px solid blue;
}

.box {
  width: 100px;
  height: 100px;
  background: red;
}

.box:first-child {
  visibility: hidden;
}
<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

但这看起来太老套了,不太对。

p8h8hvxi

p8h8hvxi1#

使用flex属性来设置灵活项的灵活长度。这样,我会告诉white-box占用所有可用空间,但第一个white-box将比正常的white -box大50%,这将取代剩余的空间

.container {
  display: flex;
  border: 3px solid blue;
}

.box {
  width: 100px;
  height: 100px;
  background: red;
}

.white-box {
  background: white;
  flex: 1;
}

.white-box:first-child {
 flex: 1.5
}
<div class="container">
  <div class="white-box"></div>
  <div class="box"></div>
  <div class="white-box"></div>
  <div class="box"></div>
</div>
7uhlpewt

7uhlpewt2#

使用CSS网格可以轻松实现这种布局

.grid-container {
  display: grid;
  grid-template-columns: auto 100px 200px 100px;
  border: 1px solid blue;
}

.grid-container > div {
  text-align: center;
  font-size: 30px;
  padding: 20px 0px;
}
.red{
  background-color: red;
}
<div class="grid-container">
  <div>1</div>
  <div class="red">2</div>
  <div>3</div>  
  <div class="red">4</div>
</div>

希望这对你有帮助

pn9klfpd

pn9klfpd3#

您需要删除

.box:first-child {
  visibility: hidden;
}
ddrv8njm

ddrv8njm4#

我也面临着同样的问题,并通过使用CSS网格找到了更好的解决方案。

.box {
  width: 100px;
  height: 100px;
  background-color: red;
}

.parent {
  display: grid;
  /*
   * Create 3 columns grid (1 ghost grid column)
   * Make first/left (ghost) and last/right column streched and center one auto width
  */
  grid-template-columns: 1fr auto 1fr;
}

.center {
  grid-column-start: 2;
  /* start your center child from 2nd column */
}

.right {
  /* Do your content right align */
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
<div class="parent">
  <div class="center">
    <div class="box">Center</div>
  </div>
  <div class="right">
    <div class="box">right</div>
  </div>
</div>

相关问题