简体   繁体   中英

Horizontal align of floating elements within a responsive div

I have an element with structure like in this fiddle , but in action it's responsive. So the width is always different and I faced a difficulty to center the LIs when the UL is smaller than default. Here's the code: [HTML]:

<ul>
    <li>Some nice text</li>
    <li>Some nice text</li>
    <li>Some nice text</li>
    <li>Some nice text</li>
    <li>Some nice text</li>
    <li>Some nice text</li>
    <li>Some nice text</li>
    <li>Some nice text</li>
</ul>

[CSS]:

ul {
width: 400px; /* <-- try to change it - li won't be centered :(*/

    overflow-x: hidden;
    overflow-y: auto;
    padding: 0 16px;
    border: 1px solid black;
}

li {
    border-radius: 5px;
    box-shadow: 0 0 15px #AAAAAA;
    float: left;
    height: 150px;
    display: inline-block;
    list-style: none;
    margin: 15px;
    padding: 10px;
    text-align: center;
    width: 100px;
}

The clear question is: how to align horizontally the floating elements in a block with responsive width?

You could align horizontally center inline-block elements by giving the parent element text-align: center; and add vertical-align (eg top) to child elements to avoid the vertical positioning issues.

Add text-align: center; to the ul and add vertical-align: top; to the li and remove the float: left; from li tag.

JSFiddle - DEMO

ul {
    width: 400px;
    overflow-x: hidden;
    overflow-y: auto;
    padding: 0 16px;
    border: 1px solid black;
    text-align: center;
}
li {
    border-radius: 5px;
    box-shadow: 0 0 15px #AAAAAA;
    height: 150px;
    display: inline-block;
    list-style: none;
    margin: 15px;
    padding: 10px;
    text-align: center;
    width: 100px;
    vertical-align: top;
}

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