targeting nth column(made by column-count)

强颜欢笑 提交于 2020-01-03 10:43:13

问题


Let's say I have this

<ul>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
</ul>


ul {
   column-count: 2;
}

and I want to align first column to right and the second to left, is there any way to target one of those columns using css selectors?


回答1:


As of now, there is no way to target nth column with pure css.




回答2:


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




回答3:


Use nth-child selector like this

ul li:nth-child(1) {
  text-align: right;
}
ul li:nth-child(2) {
  text-align: left;
}



回答4:


You can use column-gap to do what you want, though since one cannot use calc(100% - liWidth * colCount) as a value for column-count, you'd have to use some javascript right now

function calcGap() {
    var gap = window.innerWidth - (columnCount * listWidth) + "px";
    ul.style.webkitColumnGap = gap;
    ul.style.columnGap = gap;
}
calcGap(); // Fire on load
window.onresize = calcGap; // Fire on window resize

Demo

Using this method you can have whatever text-align you want as well as not messing up other alignment properties



来源:https://stackoverflow.com/questions/20955460/targeting-nth-columnmade-by-column-count

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