简体   繁体   中英

dynamic centered alignment of a ul with css

i am pulling data from database that prints in a ul li format. since data is different we may have 2 li items or we may have 10 who knows.

what is the best approach to center a ul or a div that will change in width? i know to center a div or ul i would use following:

#name, ul {
 width:200px; /*set certain width */
 margin:0 auto; /* center div */
 display:block /* play friendly with the existing layout */
}

my problem is with the data the div may be 200px or beyond 200px, and as a result it would not truly be centered, since the div center alignment is based on width.

any help would be appreciated.

Here, is a way you can center a ul that has dynamic content length.

You can wrap the ul in a div and set the CSS property on the DIV as

.wrapper{
  display:table;
  margin: 0 auto;
}

This will center align the ul inside the div irrespective of the width of the div, you can see an example below:

Codepen Link http://codepen.io/nadirlaskar/pen/RKbBpM

 .wrapper{ display:table; margin: 0 auto; background-color:yellow; } ul{ background-color:red; } li{ background-color:blue; } 
 <div class="wrapper"> <ul> <li>Item 1</li> <li>Item 2 is now large</li> </ul> </div> 

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