Targeting nth column (made by column-count)

前端 未结 4 701
孤城傲影
孤城傲影 2021-01-18 05:32

Let\'s say I have this

  • test
  • test
  • test
  • test
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-18 06:17

    It is not clear if you want to align the whole column or the elements inside.

    If you want the first one, Zach Saucier answer would be the way.

    If it's the later, and you want a CSS only solution, it would be like that:

    .container {
        -webkit-column-count: 2;
        -moz-column-count: 2;
        -ms-column-count: 2;
        column-count: 2;
    }
    
    li {
        text-align: right;
    
    }
    
    li:nth-last-child(6) ~ li:nth-child(n+4) {
        text-align: left;
        background-color: lightblue;
    }
    li:nth-last-child(8) ~ li:nth-child(n+5) {
        text-align: left;
        background-color: lightblue;
    }
    
    li:nth-child(n+4) {
        color: red;
    }
    
    li:nth-last-child(6) {
        border: solid 1px green;
    }
    

    It is based in the asumption that the elements will have the same height, and so the 2nd column will begin in the middle element.

    This solution has 2 problems.

    First, it is cumbersome to write since you need rules for every number of elements in the list.

    Second, it has a bug in the current version of Chrome, where it doesnt count properly the elements (that's why I have added extra styles to show what is going on)

    demo

    A better demo

    dynamic demo

提交回复
热议问题