Shawn
Shawn

Reputation: 11391

How can I set width using percentage and get the same width with or without a vertical scrollbar?

I have an element which I want to have width: 50%. But when the right scrollbar is there, that 50% looks different than before, and since certain elements appear and disappear (through animation), the scrollbar also appears and dissapears, dynamially changing my element's width.

See the Live Demo

Is there any way I can set an element's width with a percentage and not have it influenced by the presence or absence of a vertical scrollbar?

Upvotes: 1

Views: 1594

Answers (2)

Jason Gennaro
Jason Gennaro

Reputation: 34855

You could do something like this

Check if the height of the div is taller than the height of the window.

If so, there is a scroll. Set the width slightly wider to account for the scrollbar.

Code

$('button').click(function(){
    $('p').toggle();

    var a = $('#box');

    if(a.height() > window.innerHeight){
        $('#box').css('width', '51.7%');
    }

    else{
        $('#box').css('width','50%');    
    }              

});

Example: http://jsfiddle.net/htWrC/2/

Upvotes: 0

ScottS
ScottS

Reputation: 72261

You could make width adjustments to accommodate the scroll bar on the click, but if you are going to have a lot going on that may cause this to occur, it would probably be best to just put...

body {overflow-y: scroll;}

...and have the vertical scroll bar always be present. See http://jsfiddle.net/htWrC/1/

Upvotes: 3

Related Questions