user982853
user982853

Reputation: 2488

Javascript: 100% minus pixels

I have a div that is set to 100% but in order to fit where i need it to go i really need the size to be 100% minus 5px. I was hoping i could accomplish this by using javascript.

My current code looks like :

document.getElementById('div').style.width='100%';

but what i am trying to do is something like:

document.getElementById('div').style.width='100% - 5px';

Can anyone help me accomplish this. Thank you.

Upvotes: 0

Views: 5279

Answers (2)

nnnnnn
nnnnnn

Reputation: 150050

Regrettably you can't mix the units like that. How about using padding:

var el = document.getElementById("div");
el.style.width = "auto";
el.style.paddingRight = "5px";

Or in your CSS:

#div {
   width: auto;
   padding-right: 5px;
}

You don't want width 100% and padding because then the actual content part of the box will be at 100% with the padding outside that (and any border outside the padding that). If you use a default width it should take up the full width of the parent element and then padding pushes the content inwards.

If you're thinking "Wait a minute: I can't use padding for positioning because I need further padding within that allotted space" then I guess, much as I hate to encourage divitis, you could create an extra container div with full width and 5px padding and then put your div inside that container...

(P.S. I don't recommend giving an ID like "div" to an element, it is confusing...)

Upvotes: 1

Michael Sazonov
Michael Sazonov

Reputation: 1533

elem = document.getElementById('div');
pElem = elem.parentNode;
pPadding = pElem.style.padding || pElem.style.paddingLeft + pElem.style.paddingRight || 0;
pBorder = pElem.style.borderWidth || pElem.style.borderLeftWidth + pElem.style.borderRightWidth || 0;    
elem.style.width = ( pElem.offsetWidth - pPadding - pBorder - 5 ) + "px";

Upvotes: 1

Related Questions