简体   繁体   中英

DIV with max-width and min-width to evenly spread

I am trying to create a layout where each DIV has a max-width of 300px.

If the screen is 600px then two 100% divs should be placed next to each other. If the screen is 700px then three 233px (each DIV 100%) should be placed next to each other.

This means that the DIVs should always take up 100% of the screen width.

I would also like to have a min-width (such as 150px) so that each DIV cannot be smaller than a certain amount.

This means that on a small screen I might get two columns with DIVs and on a large scren I might get four or more columns with DIVs.

In this example you would have 4 columns when screen is larger than 900px, and it would go down to 3 columns when screen hits 900px, then 2 columns when the screen hits 600px, and one columns when it hits 300px. This will keep divs taking up 100% of screen and maximum width will always be 300px (except for screens larger than 1200px wide, where you will still get 4 columns)

  div {
    width: 25%; /* anything above 900px and there will be 4 columns */
    min-width: 150px;
    float: left;
    height: 200px;
  }

  @media screen and (max-width: 900px) {
    div { width: 33%; }
  }

  @media screen and (max-width: 600px) {
    div { width: 50%; }
  }

  @media screen and (max-width: 300px) {
    div { width: 100%; }
  }

This can be modified to have any number of columns and any number of different threshold screen sizes where number of columns will change.

If you have borders or margins you will also have to make the width %s slightly smaller.

div
{
width:33.3333%;
    min-width:150px;
    max-width:300px;
    display:inline-block;
    background:#EFEFEF;
    border:1px solid #CCC;
    height:100px;
}

I haven't tested it (today) but I think this will work until the minimum size is reached.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM