N-by-2 grid, and if the last row has only a single column, center it

我与影子孤独终老i 提交于 2019-12-02 05:41:02

问题


I want to have an N-by-2 grid like this, in which some elements (columns) might be set to display:none based on run-time factors, making the number of rows and columns unknown in advance at the design time. So it could look like this:

1 2
3 4
 5

or

1 2
4 5 (3 is missing)

or

1 3 (2, 5 is missing)
 4  (4 is the last column)

I want the last element to be always centered.

I make each div .col-xs-6 to make the grid N-by-2.

What can I do to make the last column to always be in center? Last column, which is unknown in advance at the design time, so I can't do anything particularly to it like offset it, because I can only offset all the columns because any of them could potentially be the last column.

http://jsfiddle.net/d8xwyzza/

If this isn't something that can't be done with CSS or Bootstrap alone please let me know as well.


回答1:


In your case, you can use last-child property. But you need to find the odd last element, because even last element no need to come in center place. So you can use it in the following way.

.col-xs-6
{
  display:inline-block;
  text-align:center;
}
.col-xs-6:nth-last-child(1):nth-child(odd) { /* This will find last child with odd element */
  display:inline-block;
  text-align:center;
  width:100%;
}

DEMO




回答2:


JSfiddle Demo - Option 1

Note this requires not using floats and switching to display:inline-block.

CSS

* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

.row {
    text-align: center;
    font-size:0;
}

.col-xs-6 {
    float:none;
    font-size:1rem;
    display: inline-block;
    width:50%;
    border:1px solid grey;
}

JSfiddle - Option 2

Using standard floats and clearing the last one.

* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

.row {
}

.col-xs-6 {

    border:1px solid grey;
}

.col-xs-6:nth-last-child(1):nth-child(odd) {
    clear:both;
    float:none;
    margin:0 auto;
}

EDIT: See Suresh's comment about the last child needing to be odd. Updated.



来源:https://stackoverflow.com/questions/25380567/n-by-2-grid-and-if-the-last-row-has-only-a-single-column-center-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!