📜 ⬆️ ⬇️

Adaptive speakers

When creating columns, you usually have to apply special CSS classes to the first and last element. This article is about a small trick that simplifies the layout of columns, and also makes them adaptive.

The essence of the method is reduced to the use of the nth-of-type pseudo -class : the number and width of columns varies on screens of different sizes ( Demonstration ).

Disadvantages of using classes for the first and last elements


It’s very tiring to use the .first and .last classes for the columns in each row for correct display, and there are also problems with the layout when adapting:
')


Nth-of-type usage


The expression: nth-of-type (An + B) makes it very easy to clear the floats and paddings of elements, for example:



.grid4 .col:nth-of-type(4n+1), .grid3 .col:nth-of-type(3n+1), .grid2 .col:nth-of-type(2n+1) { margin-left: 0; clear: left; } 


Adding Adaptability


To make the page adaptive, we use media queries, all values ​​in percents:

 /* col */ .col { background: #eee; float: left; margin-left: 3.2%; margin-bottom: 30px; } /* grid4 col */ .grid4 .col { width: 22.6%; } /* grid3 col */ .grid3 .col { width: 31.2%; } /* grid2 col */ .grid2 .col { width: 48.4%; } 


Here's how the transition from the four-column to the three-column grid occurs when the window is resized (less than 740px):



 @media screen and (max-width: 740px) { .grid4 .col { width: 31.2%; } .grid4 .col:nth-of-type(4n+1) { margin-left: 3.2%; clear: none; } .grid4 .col:nth-of-type(3n+1) { margin-left: 0; clear: left; } } 


The transition from four-column and three-column to two-column grid occurs with a window width of less than 600px:

 @media screen and (max-width: 600px) { /* change grid4 to 2-column */ .grid4 .col { width: 48.4%; } .grid4 .col:nth-of-type(3n+1) { margin-left: 3.2%; clear: none; } .grid4 .col:nth-of-type(2n+1) { margin-left: 0; clear: left; } /* change grid3 to 2-column */ .grid3 .col { width: 48.4%; } .grid3 .col:nth-of-type(3n+1) { margin-left: 3.2%; clear: none; } .grid3 .col:nth-of-type(2n+1) { margin-left: 0; clear: left; } } 


To stretch over the entire width, use the following code:

 @media screen and (max-width: 400px) { .col { width: 100% !important; margin-left: 0 !important; clear: none !important; } } 


Work in Internet Explorer


In Internet Explorer 8 and earlier, media queries and nth-of-type are not supported. To solve this problem, you can use selectivizr.js (fixed nth-of-type) and respond.js (fixed media queries). unfortunately, selectivizr.js and respond.js do not work very well together: nth-of-type will not work inside media queries.

Source: https://habr.com/ru/post/161923/


All Articles