Justin D.
Justin D.

Reputation: 4976

Javascript - Dynamic div width depending on page size

I need to set the width of a div depending on the page size.

I have three columns. The first and third ones are 50px fixed. I need to set my middle one so it will take all the space with a small margin. I haven't found how to do it in CSS. So I tried using Javascript with window.innerWidth and subtracting the two 50px.

Here is my CSS :

<div class="col1">
    ...
</div>
<div class="col2">
  <div class="col2-1">
    ...
  </div>
<div class="col2-2">
    ...
</div>
</div>

And the corresponding Javascript

<script type="text/javascript">
  setStoreInfoWidth = function () {
    $('div.col2-1').css('width', window.innerWidth-100 + 'px')
  };

  setStoreInfoWidth();

  $(window).resize(function () {
    setStoreInfoWidth();
   });
</script>

Here is a JsFiddle with the code working : http://jsfiddle.net/MrYUb/

However, I can't make it work on my actual website.

Do you have any idea why?

Upvotes: 0

Views: 342

Answers (2)

teynon
teynon

Reputation: 8318

You can use negative margins to create a 3 column layout:

http://jsfiddle.net/teynon/J2mx7/2/

<div class="container">
    <div class="leftCol">
        Left stuff
    </div>
    <div class="rightCol">
        Right Stuff
    </div>
    <div class="middleCol">
        Middle stuff
    </div>
</div>
<div style="background-color: #0000BB; clear: both;">Test</div>

CSS:

.container {
    width: 100%;
    position: relative;
}

.leftCol {
    float: left;
    margin-right: -50px;
    width: 50px;
    left: 0px;
    min-height: 100px;
    background-color: #FF0000;
}

.rightCol {
    width: 50px;
    margin-left: -50px;
    right: 0px;
    min-height: 50px;
    background-color: #00FF00;
    float: right;
}

.middleCol {
    margin: 0px 55px 0px 55px;
    background-color: #0000FF;
    min-height: 50px;
}

Upvotes: 2

Thomas Junk
Thomas Junk

Reputation: 5676

Why not using percent? If you have 2 divs, that 'll make 50% for each.

Upvotes: 0

Related Questions