I'm displaying a list of same sized items in a flex div. I've aligned them to the left. However I'd like the list to be centred as a whole. Any suggestions about how to do this?
Please try to snipped below.
$('button').click(function(){ $('.list').toggleClass('hack') });
.item { width: 40px; height: 40px; background-color: skyblue; border: 1px solid black; } .list-container { width: 100px; background-color: grey; flex-direction: row; display: flex; } .spacer { flex: 1; } .list.hack { width: 84px; } .list { display: inline-flex; flex-direction: row; flex-wrap: wrap; background-color: yellow; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='list-container'> <div class='spacer'></div> <div class='list'> <div class='item'></div><div class='item'></div> <div class='item'></div><div class='item'></div> <div class='item'></div> </div> <div class='spacer'></div> </div> <button>Toggle fixed list width (hack)</button>
I believe the best way is to insert the "item" elements to a new div, setting:
<div style="margin:0 auto;width: 85px;">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
and also applying .item{float:left;}
It's not enough when you set justify-content: center; to .list ?
Then if you need to make the standalone item to be aligned to left, you can set its margin-right: 42px; (to compensate the space next to it)
You can do the same without using flex
HTML
<div class='list'>
<div class='item'>item 1</div><div class='item'>item 2</div>
<div class='item'>item 3</div><div class='item'>item 4</div>
<div class='item'>item 5</div>
</div>
CSS
.list{
display:inline-block;
background-color: grey;
width:100px;
clear:both;
justify-content: center;
}
.list .item{
float:left;
width:48%;
background-color: skyblue;
height: 40px;
border: 1px solid black;
}
.list .item:last-child{
margin-left:25%;
}
Click here for JSFiddle sample
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.