简体   繁体   中英

Make div width 100% when the div next to it is pushed down the page

CSS gurus, I'm back with another probably lame question. I have two divs next to eachother. I want to meet the following two conditions:

  1. When there is enough space for both on the page, they should have 50% width and be on the same row.
  2. When there isnt enough space - they should be 100% width and on top of eachother.

Here is a JSFiddle: https://jsfiddle.net/kwg1upu0/5/

HTML:

<div class="container">
 <div class="divOne"></div>
 <div class="divTwo"></div>
</div>

CSS:

.container {
  width: 100%;
}

.divOne { 
  width: 50%;
  min-width: 300px;
  height: 100px;
  background-color: yellow;
  float: left;
}

.divTwo {
  width: 50%;
  min-width: 300px;
  height: 100px;
  background-color: blue;
  float: left;
}

EDIT: Indeed Media Queries are the correct answer which I marked. Keep in mind that media queries will only apply on page load, so the change won't happen dynamically as you resize the window. In my case I need that, so I will have to do it programatically with Angular and $window.innerWidth.

You can use a media query.

 .container { width: 100%; } .divOne { width: 50%; height: 100px; background-color: yellow; float: left; } .divTwo { width: 50%; height: 100px; background-color: blue; float: left; } @media (max-width: 600px) { .divOne, .divTwo { width: 100% !important; } } 
 <div class="container"> <div class="divOne"></div> <div class="divTwo"></div> </div> 

I think the only way to do this properly is with media queries. See fiddle: https://jsfiddle.net/kwg1upu0/6/

@media screen and (max-width:600px) {
  .divOne, .divTwo {
    width:100%;
  }
}

Once the width of the page is 600px or less, then change it to 100% 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