0

Lets say i have this html

.container {
height: 50px;
width: 100%;

display: flex;
justify-content: space-between;
}


.left {
height: 50px;
width: 20%;
background: red;
}

.middle {
height: 50px;
width: 20%;
background: yellow;
}


.right {
height: 50px;
width: 20%;
background: blue;
}

.real-center {
width: 20%;
margin: auto;
height: 50px;
background: lightgreen;
text-align: center;
}
<div class='container'>

<div class='left'></div>
<div class='middle'></div>
<div class='right'></div>

</div>

<br/>
<div class='container'>
<div class='real-center'>This is Real Center</div>
</div>

So my main goal is left always at the start, middle always center and right always stick at the end of the container.

So if the width of all div the same ( or at least the width of left and right are the same), this can be achieved. However, if the width of these divs are different, space-between no longer be able to achieve this. For example

.container {
height: 50px;
width: 100%;

display: flex;
justify-content: space-between;
}


.left {
height: 50px;
width: 10%;
background: red;
}

.middle {
height: 50px;
width: 50%;
background: yellow;
}


.right {
height: 50px;
width: 20%;
background: blue;
}

.real-center {
background: lightgreen;
height: 50px;
width: 50%;
margin:auto;
text-align:center;
}
<div class='container'>

<div class='left'></div>
<div class='middle'></div>
<div class='right'></div>

</div>


<br/>
<div class='container'>
<div class='real-center'>This is Real Center</div>
</div>

As you can see the middle div (yellow) is no longer at the center of the container.

IS there any css that can make yellow div always at center, regardless the width of the 3 children. Thanks

P/s: as the width of all of 3 divs may change alot, so i try solutions with position (relative,absolute), or adding some margin, it may not work for all cases, so im looking for a more general solution, that auto center this, thanks

Jake Lam
  • 2,674
  • 3
  • 19
  • 40
  • If you make the yellow `div` center the UI is ugly – Posandu Oct 07 '21 at 07:33
  • @ŕ̷͉ge̸ḓ̶̅i̷t for my case, the yellow div is like the Webpage Title, so it has to be at the center. – Jake Lam Oct 07 '21 at 07:40
  • then you need to use columns for this https://www.w3schools.com/bootstrap/bootstrap_grid_system.asp#:~:text=Bootstrap's%20grid%20system%20allows%20up%20to%2012%20columns%20across%20the%20page.&text=Tip%3A%20Remember%20that%20grid%20columns,stack%20no%20matter%20the%20viewport. – Aman Sharma Oct 07 '21 at 07:41
  • @AmanSharma if i use columns, i need to specify the region of left,middle, and right right . Im more like dont want to do that, because their width is quite dynamic. I just want middle to always at the center, left stick to left side and right stick to right side – Jake Lam Oct 07 '21 at 07:55

0 Answers0