Home > Enterprise >  CSS grid columns according to screensize
CSS grid columns according to screensize

Time:04-14

I'm trying to use CSS grid and the columns should behave like this:

  • on a mobile-screen I want one column witch has the full width. That column includes two sections. In the first section there are multiple input fields (also only one column). In the second section there are two columns with smaller input fields.
  • on a bigger screen (1024px or wider) there should be two columns so that the two sections are next to each other, while the first section should be smaller than the second. In the first section the input fields are now in two columns, in the second section the input fields are in three columns.

I hope that makes sense :)

What I have right now kind of works but the two sections have the same width. I don't really want it that way because like that the second section is "jumping up" very late if the screen gets wider. So if I have a browser-width of for example 800px then there is a lot of white space on the right of the first section even though the second section could fit next to it.

This is what I've got so far:

.surrounding-div {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(min(260px, 50%), max(600px, 50%)));
};
.first-section {
    display: grid;
    grid-template-columns: repeat(auto-fit, 200px);
    grid-column-gap: 1rem;
}
.second-section {
    display: grid;
    grid-template-columns: repeat(auto-fit, 150px);
    grid-column-gap: 1rem;
}

It is possible that this is a really bad approach, since this is only the second time that I really work with grids. I'm not even sure anymore if a grid is the right thing to use here.

If possible, I want to accomplish this without using Media Queries

CodePudding user response:

You can use @media screen for that. For example:

@media screen and (max-width: 600px) {
  CSS Code here will only be executed on a screen with a width below 600px
}

Using this you can set the size of each column. This might help you as well: https://www.w3schools.com/css/css3_mediaqueries_ex.asp

CodePudding user response:

You can use media queries.

.grid_parent{
    display: grid;
    grid-template: number of rows/ xfr yfr; /*This is in the form is rows/columns. Since you want one column to be larger, make either x or y larger*/

/*Now initialize the grid elements in whatever way you want*/
.grid_element{
    grid-column: startcolumn/ endcolumn;
    grid-row: startrow / endrow;

/*Now the layout for the smaller screen*/
@media all and (max-width: 600px) {
    .grid_parent{
        grid-template: number of rows you want/ 1fr; /*The 1fr is important since you only want one column*/

    /*Now initialize the grid-elements as you did previously*/
    ....
    ....
}

If you're not too familiar with media queries or the 'fr' concept, google it and if you still have some doubts, do pop a comment. I'll edit my answer to include them.

  • Related