Home > Blockchain >  Align active button centre in a Flex div
Align active button centre in a Flex div

Time:12-31

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 >
  <h4>HELLO</h4>
  <div >
    <button >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.

CodePudding user response:

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 >
  <h4>HELLO</h4>
  <div >
    <button >ONE</button>
    <button>TWO</button>
    <button>THREE</button>
  </div>
</div>
<div >
  <h4>HELLO</h4>
  <div >
    <button >ONE</button>
    <button >TWO</button>
    <button>THREE</button>
  </div>
</div>
<div >
  <h4>HELLO</h4>
  <div >
    <button >ONE</button>
    <button >TWO</button>
    <button >THREE</button>
  </div>
</div>

CodePudding user response:

one of easiest way is use padding:

.flexbox {
    width: 100%;
    justify-content: center;
    padding-left: 3.2rem;
}
  • Related