0

I have a simple HTML code which contains three button inside a flex div as bellow; When a user click on any of the buttons, that button will have the active class.

.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>

What I need to achieve here is the button contain the active class should always be centre aligned in side the flex box.

According to the above, the button ONE has the active class and it should be centre aligned in side the flexbox and other two buttons should go right.

You can get the idea from the image below

enter image description here

NOTE: Preferred to solve this with use CSS only.

mapmalith
  • 1,303
  • 21
  • 38

1 Answers1

1

If it's only 3 buttons here is an idea using CSS grid:

.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>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415