How can I center <ul> <li> into a div?
For centering a <ul> in a div, apply CSS flexbox: set the div to display: flex;, and use justify-content: center; for horizontal alignment and align-items: center; for vertical centering. Here's your snippet:
The ul appears perfectly centered in the div. Adjust height to suit your needs.
Common techniques for centering
Using display: inline-block
Render a <ul> as inline-block and set text-align: center; on the parent div. This method is useful when you want to take advantage of block-like features while fitting the content width.
Working with list items (li)
For horizontal alignment of li elements, set display: inline;, handy for a horizontal menu:
For more advanced layouts, like that tasty responsive menu, wrap each li in its own div with display: flex;.
Flexing with Responsive Design
For responsive design, use percentage widths. Fixed widths can be obstinate, potentially restricting centering, especially on smaller screens.
Dealing with IE
Ensure IE compatibility with the backup singers, zoom: 1; *display: inline; ready to save the day.
The finer details
Dealing with defaults
The <ul> element comes built-in with padding and margin. Remember to reset these attributes to ensure your centering is on point:
Safe coding rules
Avoid using width when centering with padding and margin, as a fixed width can misalign your centering. Floating elements might look cool but can disrupt your layout:
Keeping HTML clean
Ensure to keep your HTML structure clean by applying styles that do not conflict with your desired centering. Say no to inline styles; use CSS classes instead to keep your markup neat and tidy.
Was this article helpful?