<div class="imgcontainer">
<ul>
<li><img src="1.jpg" alt="" /></li>
<li><img src="2.jpg" alt="" /></li>
.....
</ul>
</div>
I'm coding a simple gallery page by creating unordered list and each list item of it contains an image.
ul li {
float: left;
}
I set the width of the container as "max-width" so I can make possible to fit the list items (images) to the browser width.. meaning that they will be re-arranged when the browser window re-sized.
.imgcontainer{
max-width: 750px;
}
Now the problem is those images or list items are not aligned to center, they are aligned to the left of .imgcontainer body (colored gray in the attached link below), leaving a space on the right when the window re-sized!
How can I center those images every time the window resized?
Here's the whole page/code you can preview it or edit it at JS Bin
http://jsbin.com/etiso5
All that needs to be done is to set your <ul> or <ol> as position: relative; so it holds down the fort, display: block; so it takes up the space, and then give it a text-align: center; Next, tell your <li> to have a width: auto; and to, and this is the magic, display: inline; Works every time, palm to forehead.
Center a ul inside a div using CSS grids In this method, all you need to do is put the <ul> inside a div element and then make it a grid container by applying display: grid; on it.
The CSS float property is used to set or return the horizontal alignment of elements. But this property allows an element to float only right or left side of the parent body with rest of the elements wrapped around it. There is no way to float center in CSS layout.
Just give the list centered text (e.g. ul. nav { text-align: center; } ) and the list items inline-block (e.g. ul. nav li { display: inline-block; } ). If you want to do it with margin for whatever reason, look into width: fit-content; .
Remove float:left
and use display:inline
so that you can use text-align:center
. Set the font size to zero so that you don't have white-space between the images.
ul {
font-size:0;
text-align:center
}
ul li {
display:inline;
zoom:1
}
.imgcontainer {
max-width:750px;
margin:0 auto
}
The zoom
is a hack for old IE versions. This is however not a valid CSS property, so won't go through the W3C validator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With