【问题标题】:How to center a flex item? [duplicate]如何使弹性项目居中? [复制]
【发布时间】:2023-12-07 09:19:02
【问题描述】:

我希望 ABCD 在左边,DATE 应该在中间。如何做到这一点?

.flex-items {
  display: flex;
  justify-content: flex-start;
  padding-left: 17px;
}

.abcd1 {}

.date1 {
  /*this item should be in the center.*/
}
<div class="flex-items">
  <div class="abcd1">ABCD</div>
  <div class="date1">DATE</div>
</div>

【问题讨论】:

  • 保证金:自动日期

标签: html css flexbox centering


【解决方案1】:

试试这个代码

.flex-items {

  display: flex;
  justify-content: flex-start;
  padding-left: 17px;
}

.abcd1 {

}

.date1 {
    margin-left: auto;
    margin-right: auto;
}
<div class="flex-items">

<div class="abcd1">ABCD</div>
<div class="date1">DATE</div>

</div>

【讨论】:

  • 太好了,谢谢:)
  • text-align 在这里没用
  • 是的,我们可以在这里删除 text-align。
  • 是的,我已将其删除。
  • 此解决方案不会将 DATE 置于整行的中心。它仅在行的剩余空间中将 DATE 居中。 DATE 偏离中心(向右)ABCD 元素的长度。 jsfiddle.net/5wm9e0d0/1
【解决方案2】:

见下文。希望这会有所帮助。

.flex-items {
  display: flex;
  padding-left: 17px;
  text-align: center;
}

.date1 {
  flex: 1;
}
<div class="flex-items">
  <div class="abcd1">ABCD</div>
  <div class="date1">DATE</div>
</div>

【讨论】:

  • margin-right 在这里没用
  • 感谢@TemaniAfif。代码调整。
【解决方案3】:

文本对齐:中心在提供宽度时起作用。 这也有效:

.flex-items {
     display: flex;
     justify-content: flex-start;
     padding-left: 17px;
}
.abcd1 {
          
}     
.date1 {
     /*this item should be in the center.*/
     text-align: center;
     width: 100%;
}
    <div class="flex-items">
    <div class="abcd1">ABCD</div>
    <div class="date1">DATE</div>
</div>

【讨论】: