简体   繁体   中英

Div not getting displayed into 4 column and shrinking into 2 when adjusting window size

I have got a div which has 4 items and want to display them in a single row for large devices. It does display as I want, but there is a scroll bar on the page which makes this annoying. I need to scroll from left to right to see all the items if that makes sense.

Here's the code:

 .container { display: flex; width: 100%; height: 534px; } @media only screen and (max-device-width: 1080px) { .container { flex-direction: row; flex-wrap: wrap; width: 100%; } } .item{ width: 250px; position: relative; margin: 50px auto; }
 <div class="container"> <div class="item">1</div> <div class="item">1</div> <div class="item">1</div> <div class="item">1</div> </div>

You have several options depending on exactly what outcome you want.

The simplest is to just allow the items (which have a fixed width) to wrap to the next line when the window is too small to accommodate them all. This means you may sometimes get 3 on the first line and 1 on the second.

With more control you can switch to making sure there are either 4 or 2 (or, on really narrow windows, 1) item in a row.

This snippet uses a grid to do this with breakpoints set using max-width (see note below).

 .container { display: grid; grid-template-columns: repeat(4, 1fr); width: 100%; height: 534px; } @media only screen and (max-width: 1080px) { .container { grid-template-columns: repeat(2, 1fr); } } @media only screen and (max-width: 270px) { .container { grid-template-columns: repeat(1, 1fr); } } .item { width: 250px; position: relative; margin: 50px auto; }
 <div class="container"> <div class="item">1</div> <div class="item">1</div> <div class="item">1</div> <div class="item">1</div> </div>

Note: device-width is deprecated (see for example [https://developer.mozilla.org/en-US/docs/Web/CSS/@media/device-width][1]

And the width of a device is not really relevant - what we need to adjust for is the width of the window. This is done in a media query with max-width.

Note also that both your original code and this snippet lessen the height of each item for narrower viewports as you have set a fixed height for the container. If you want the items to maintain full height then set height on the item (or adjust the height of container accordingly). [1]: https://developer.mozilla.org/en-US/docs/Web/CSS/@media/device-width

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