sizing div based on window width

loriensleafs picture loriensleafs · Apr 9, 2012 · Viewed 261.7k times · Source

I have kind of a weird question. On my page I have a main image of a planet in some heavy duty nebula. I have it set up so the min width is 1000px and max is 1500px. I have the sides fading out and this looks great with larger screens. What I'd like to try to do is when you're looking at it on a mobile device for example and it's cutting off the width at 1000 pixels, I'd like the image say 1300 pixels wide, centered and 150 pixels is cut off each side so you can't see the fade out at all, but is still able to then enlarge is the window's width becomes larger say on like a large iMac and that fade then becomes visible again once you pass that 1300 pixel width.

My initial thought was to do something with negative margins on either side, but I couldn't get this to work while keeping the max and mix widths.

This is that specific section of code from the page, though the html and css is right there for everyone to see, you can just use the fine command to find that div ID for any further looking.

<div style="position:relative;width:100%;">
   <div id="help" style="
      position:relative;
      z-index:1;
      height:100%;
      min-width: 1000px;
      max-width: 1500px;
      margin: 0 auto;
   ">
      <img src="http://i.stack.imgur.com/tFshX.jpg" border="0" style="width:100%;">
   </div>
</div>

Any thoughts on this, it's very close to working the way I'd like it to, just needs a small tweak.

Answer

atilkan picture atilkan · Feb 6, 2016

Viewport units for CSS

1vw = 1% of viewport width
1vh = 1% of viewport height

This way, you don't have to write many different media queries or javascript.

If you prefer JS

window.innerWidth;
window.innerHeight;