CSS dynamic responsive column layout

断了今生、忘了曾经 提交于 2019-12-04 07:23:21

Although you are using items and not text- the below will still work, simply wrap the items into a container with the below CSS applied (replace div with the id or class of this container).

Have a look at the below- the columns will automatically compress at a smaller screen size without the need to media queries.

Demo Fiddle

CSS:

html, body {
    width:100%;
}
div {
    -webkit-column-width: 20em;
    -webkit-column-gap: 2em;
    -webkit-column-rule: 1px solid #eee;
    -webkit-column-count: 2;
    -moz-column-width: 20em;
    -moz-column-gap: 2em;
    -moz-column-rule: 1px solid #eee;
    -moz-column-count: 2;
    -ms-column-width: 20em;
    -ms-column-gap: 2em;
    -ms-column-rule: 1px solid #eee;
    -ms-column-count: 2;
    column-width: 20em;
    column-gap: 2em;
    column-rule: 1px solid #eee;
    column-count: 2;
}

Alternatively- with Media Queries

If you want more control- you can simply use a media query to apply columns at sizes above that specified (below being 1024)

html, body {
    width:100%;
}
@media screen and (min-width: 1024px){
    div {
        -webkit-column-width: 20em;
        -webkit-column-gap: 2em;
        -webkit-column-rule: 1px solid #eee;
        -webkit-column-count: 2;
        -moz-column-width: 20em;
        -moz-column-gap: 2em;
        -moz-column-rule: 1px solid #eee;
        -moz-column-count: 2;
        -ms-column-width: 20em;
        -ms-column-gap: 2em;
        -ms-column-rule: 1px solid #eee;
        -ms-column-count: 2;
        column-width: 20em;
        column-gap: 2em;
        column-rule: 1px solid #eee;
        column-count: 2;
    }
}

Preventing elements from breaking between columns

To avoid elements from being broken between columns, you can use the below:

.group{ /* class to restrict breaking on */
    break-inside: avoid-column;
    -webkit-column-break-inside: avoid;
    page-break-inside: avoid;
    overflow: hidden; /* optional */
    display:inline-block; /* optional */
}

That said, note that functionality support between browsers may be patchy, if it isnt working as expected, replace display:inline-block; with display:table; or remove entirely.

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