Explain Codes LogoExplain Codes Logo

How can I center <ul> <li> into a div?

html
responsive-design
css
centering
Alex KataevbyAlex Kataev·Oct 15, 2024
TLDR

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:

<div style="display: flex; justify-content: center; align-items: center; height: 100px;"> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> </div>

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.

div { text-align: center; /* Having a straight day */ } ul { display: inline-block; /* Not feeling so blocky today */ padding: 0; /* Diet day */ margin: 0; /* Living on the edge */ }

Working with list items (li)

For horizontal alignment of li elements, set display: inline;, handy for a horizontal menu:

li { display: inline; /* I prefer sideways */ margin-right: 10px; /* Social distancing */ }

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.

ul { width: 80%; /* Room for all */ margin-left: auto; /* Lazy positioning left */ margin-right: auto; /* Lazy positioning right */ }

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:

ul { padding: 0; /* No love handles */ margin: 0; /* No external affairs */ }

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:

ul { /* Avoiding if using flexbox for centering */ float: left; /* Try swimming instead */ }

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.