The easiest way to center a ul
and all of its li
inside of a div
is to use the text-align: center;
property on the containing <div> element.
However, if you have already tried this, it would haven’t worked. This is because <ul>
is a block-level element and applying text-align: center;
on such elements’ container has no effect.
But, if you make the <ul>
an inline or inline-block element and then apply text-align: center;
on the containing element, it would center the ul inside of it.
Here is a working example:
Example:
div{ text-align: center; } ul{ display: inline-block; text-align: left; }
Center a ul inside a div using CSS grids
CSS grids are always the best alternative in terms of centering things both horizontally as well as vertically.
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.
Now, to center the grid items horizontally you can use the justify-content: center;
and to center them vertically, you can use align-items: center;
Here is a working example:
Example:
div{ display: grid; justify-content: center; }