【问题标题】:Align active button centre in a Flex div在 Flex div 中对齐活动按钮中心
【发布时间】:2021-12-31 16:07:45
【问题描述】:

我有一个简单的 HTML 代码,它在 flex div 中包含三个按钮,如下所示; 当用户单击任何按钮时,该按钮将具有 active 类。

.box {
  width: 100%;
  background-color: red;
  text-align: center;
}

.flexbox {
  width: 100%;
  justify-content: center;
}

.active {
  background-color: yellow;
}
<div class="box">
  <h4>HELLO</h4>
  <div class="flexbox">
    <button class="active">ONE</button>
    <button>TWO</button>
    <button>THREE</button>
  </div>
</div>

我需要在这里实现的是包含active 类的按钮应该始终在flex box 旁边居中对齐。

根据上述,按钮 ONE 具有 active 类,它应该在 flexbox 旁边居中对齐,其他两个按钮应该向右。

你可以从下面的图片中得到这个想法

注意:最好仅使用 CSS 来解决此问题。

【问题讨论】:

标签: html css


【解决方案1】:

如果这里只有 3 个按钮,这是一个使用 CSS 网格的想法:

.box {
  background-color: red;
  text-align: center; /* center the grid */
}

.flexbox {
  display: inline-grid;
  grid-template-columns: repeat(5, 1fr); /* 5 columns */
  justify-content: center; /* center the columns */
  gap: 5px;
}

.active {
  grid-column: 3; /* active always on the middle */
}
/* we need a "hacky" code for the second case */
.active:nth-child(2) {
  grid-area:1/1;
  transform:translate(calc(200% + 10px)); /* 10px = 2xgap */
}
.active:nth-child(2) ~ :last-child {
  grid-column:4;
}
<div class="box">
  <h4>HELLO</h4>
  <div class="flexbox">
    <button class="active">ONE</button>
    <button>TWO</button>
    <button>THREE</button>
  </div>
</div>
<div class="box">
  <h4>HELLO</h4>
  <div class="flexbox">
    <button >ONE</button>
    <button class="active">TWO</button>
    <button>THREE</button>
  </div>
</div>
<div class="box">
  <h4>HELLO</h4>
  <div class="flexbox">
    <button >ONE</button>
    <button >TWO</button>
    <button class="active">THREE</button>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2022-09-23
    • 2022-10-01
    • 2021-10-24
    • 2019-03-25
    • 2019-08-07
    • 2018-10-31
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多