简体   繁体   English

响应div中浮动元素的水平对齐

[英]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. 因此宽度总是不同的,并且当UL小于默认值时,我很难将LI居中。 Here's the code: [HTML]: 这是代码:[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]: [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; 您可以通过将父元素设置为text-align: center;来将行inline-block元素水平居中text-align: center; and add vertical-align (eg top) to child elements to avoid the vertical positioning issues. 并向子元素添加vertical-align (例如,顶部),以避免垂直定位问题。

Add text-align: center; 添加text-align: center; to the ul and add vertical-align: top; ul并添加vertical-align: top; to the li and remove the float: left; li并移除float: left; from li tag. li标签。

JSFiddle - DEMO JSFiddle- 演示

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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