简体   繁体   中英

How can I set single child element in center align using css?

I have multiple child element in parent that divided with 3 columns and from 4 element goes to second row with left align:

 ul { list-style: none; display: flex; align-items: center; justify-content: flex-start; flex-flow: wrap; } li { width: 33.33%; flex: 0 0 33.33%; padding: 15px 0; background: #000; color: #fff; font-size: 1rem; text-align: center; margin-bottom: 15px; }
 <ul> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Four</li> </ul>

But, when I have only a single child in my <ul> list, I want single child column into center.

Since the maximum number per row is 3 you can handle each case alone. You have only 2:

 ul { list-style: none; display: flex; align-items: center; flex-flow: wrap; padding:0; margin:5px; } li { flex: 0 0 33.33%; padding: 15px 0; background: #000; color: #fff; font-size: 1rem; text-align: center; margin-bottom: 15px; } /*1 item */ li:only-child { margin:auto; } /*2 item */ li:nth-child(1):nth-last-child(2) { margin-left:auto; } li:nth-child(2):nth-last-child(1) { margin-right:auto; }
 <ul> <li>One</li> </ul> <ul> <li>One</li> <li>Two</li> </ul> <ul> <li>One</li> <li>Two</li> <li>Three</li> </ul> <ul> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Four</li> </ul>

You can use CSS 3 Flexbox to achieve your specific requirement.

 ul { display: flex; width: 150px; flex-flow: row wrap; justify-content: space-around; }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <ul> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Five</li> </ul> <ul> <li>One</li> </ul> <ul> <li>One</li> <li>Two</li> </ul> <ul> <li>One</li> <li>Two</li> <li>Three</li> </ul> </body> </html>

Ref: https://www.w3schools.com/css/css3_flexbox.asp

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