简体   繁体   中英

Trouble horizontally centering <div> containing <ul>

I can't seem to get my list to center. The li elements center just fine but it seems that I can't get my ul to center on the page.

I need the ul or the ul's container to be width: 100%; for I want to have a background for the ul which should stretch to fill the page width and the ul+margin height.

I have looked around the webb but no answers seem to fit my needs, this is my first question and I'm new to this scene so please be understanding if I've done anything wrong.

HTML (with php to be used in Wordpress)

<div class="body-news">
    <ul id="newsbar">   
            <li>
                <?php dynamic_sidebar( 'in-body-widget-area' ); ?>
            </li>
            <li>
                <?php dynamic_sidebar( 'in-body-widget-area2' ); ?>
            </li>
            <li>
                <?php dynamic_sidebar( 'in-body-widget-area3' ); ?>
            </li>
    </ul>
</div>

CSS

.body-news{
}
    .body-news ul{
        margin: 0 auto;
        overflow: hidden;
        text-align: center;
    }
        #newsbar li{
            text-align: left;
            float: left;
            display:inline;
            width: 300px;
            margin: 15px 20px;
        }

One simple solution is to remove text-align: left from li elements and use display: table to ul :

 .body-news { } .body-news ul { margin: 0 auto; overflow: hidden; text-align: center; display: table; } #newsbar li { float: left; display:inline; width: 300px; margin: 15px 20px; } 
 <div class="body-news"> <ul id="newsbar"> <li> <p>Widget1</p> </li> <li> <p>Widget2</p> </li> <li> <p>Widget3</p> </li> </ul> </div> 

You need to remove the float on the list items and change them to inline-block .

    #newsbar li{
        text-align: left;
        display: inline-block;
        max-width: 300px;
        margin: 15px 20px;
    }

Updated fiddle: http://jsfiddle.net/0g9z5mmw/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM