Home > Web Front-end > CSS Tutorial > How to Center an Unordered List (``) Inside a Div?

How to Center an Unordered List (``) Inside a Div?

Patricia Arquette
Release: 2024-12-26 11:06:10
Original
298 people have browsed it

How to Center an Unordered List (``) Inside a Div?

How to Horizontally Align ul to Center of div?

When faced with centering an unordered list (

    ) within a div using CSS, there are several solutions to tackle this challenge. Here's a breakdown of the provided CSS and suggested methods to achieve your desired result:

    The given CSS:

    .container { 
        clear: both; 
        width: 800px; 
        height: 70px; 
        margin-bottom: 10px;
        text-align: center;
    }
    
    .container ul { 
        padding-left: 20px; 
        margin: 0; 
        list-style: none;
    }
    
    .container ul li { 
        margin: 0; 
        padding: 0; 
    }
    Copy after login

    With the property text-align: center; applied to .container, it appears that you're aiming to center everything within the container, including the ul. However, this property only aligns the text content of an element, not the element itself.

    Here are some approaches to horizontally center your ul within the div:

    Solution 1: Using margin's auto:

    This method involves setting the margin: 0 auto; on the ul, allowing it to have margins applied symmetrically, effectively placing it in the center:

    .container ul {
        margin: 0 auto;
    }
    Copy after login

    Solution 2: Utilizing display: table;:

    This solution takes advantage of the table rendering mode of the display property. By setting display: table; on the ul, you transform it into a table container. Then, margin: 0 auto; will center the ul within the div the same way as in Solution 1:

    .container ul {
        display: table;
        margin: 0 auto;
    }
    Copy after login

    Solution 3: Implementing text-align: center; and inline-block:

    This method makes use of the display: inline-block; property on the ul. When combined with text-align: center; on the parent container, it places the ul in the center as an inline element within the text flow:

    .container { 
        text-align: center;
    }
    
    .container ul { 
        display: inline-block;
    }
    Copy after login

    The above is the detailed content of How to Center an Unordered List (``) Inside a Div?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template