简体   繁体   English

如何将元素置于容器中心,同时保持它们垂直对齐?

[英]How do I center element within a container while keeping them vertically aligned?

Not really sure how to properly title this. 不确定如何正确地标题这个。 It is best explained with images. 最好用图像解释。 I am trying to keep the items centered, but when there is too many to fit properly on one line, the new line should be aligned with the item above it, not centered within the container. 我试图将项目保持在中心位置,但是当在一行上有太多不能正确匹配时,新行应与其上方的项目对齐,而不是在容器中居中。

I am trying to achieve this: 我想要实现这个目标:

在此输入图像描述 Instead of this: 而不是这个:

在此输入图像描述

Here is my JSfiddle: 这是我的JSfiddle:

http://jsfiddle.net/6kwzy6La/ http://jsfiddle.net/6kwzy6La/

And my HTML: 我的HTML:

<div class="container2">
    <div class="content">

        <div id="box">
            <p> Some text goes here </p>
        </div>

        <div id="box">
            <p> Some text goes here </p>
        </div>

        <div id="box">
            <p> Some text goes here </p>
        </div>

        <div id="box">
            <p> Some text goes here </p>
        </div>

        <div id="box">
            <p> Some text goes here </p>
        </div>

    </div>
</div>

http://jsfiddle.net/6kwzy6La/ http://jsfiddle.net/6kwzy6La/

Container1
{
text-align: center;
}

Container2
{
text-align: left;
}

One approach is to add an appropriate right margin to the last box if there are a odd number of boxes, like this 一种方法是在最后一个框中添加适当的右边距,如果有奇数个框,就像这样

#box:last-child:nth-child(2n + 1) {
    margin-right:240px;
}

See http://jsfiddle.net/6kwzy6La/6/ http://jsfiddle.net/6kwzy6La/6/

Note that you should be using class not id as id s should be unique within the document. 请注意,您应该使用class not id因为id在文档中应该是唯一的。

暂无
暂无

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

相关问题 如何将我的项目符号列表移动到中心,同时让它们在 CSS 中垂直对齐? - How do I move my bullet list to the center while having them vertically aligned in CSS? 如何垂直居中 li 导航菜单但将其水平对齐到右侧,同时保持徽标图标水平对齐左和 ctrd vert? - How do I vertically center li navigation menu but horizontally align it to the right while keeping logo icon horizontally aligned left and ctrd vert? 如何<a>在flex div中</a>垂直居中<a>元素?</a> - How do I vertically center an <a> element within a flex div? 如何将3个100x100px的div垂直和水平居中,同时将它们排成一行 - How can I vertically and horizontally center 3 100x100px divs while keeping them in row 如何在保持页脚的同时将 flex 容器定位为垂直和水平对齐? - How do I position a flex container to be vertically and horizontally aligned while maintaining a footer? 如何将文字和图片垂直居中对齐 - How do I center aligned vertically the text with my image 将ul放在容器中居中,同时使li内侧对齐 - Center ul in container while keeping li inside left aligned 如何在保持容器左对齐的同时缩小容器并使其居中? - How shrink and center a container while keeping it's contents left-aligned? 我的标签页向左对齐...如何将它们移到中心? - My tabs are aligned left…how do I moved them to the center? 中心元素,左对齐元素在容器内嵌入 - Center element with left aligned element inline within container
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM