I have following code:
<div style="border:4px solid black;width:100%;height:100px;position:fixed;left:250px;">
out of bound :(
</div>
I want it not to cross the window. I need its right border to stay visible.
JSFiddle link: http://jsfiddle.net/9SZAB/
Remove the width
property and instead use right: 0
:
div {
border:4px solid black;
height:100px;
position:fixed;
left:250px;
right: 0;
}
Updated fiddle: http://jsfiddle.net/9SZAB/2/
Why this works: position: fixed
tells the element to have a fixed position relative to the viewport, so that the positioning properties left
, right
, top
, and bottom
, as well as width
and height
will position and size the element based on the size and boundaries of the viewport.
Previously you had width: 100%
, which, combined with position: fixed
, means that the element's width should be 100% of the viewport's width. This width is not and should not be affected by any margins or positioning that you also set - the element will still have 100% of the viewport's width, no matter where it is.
But if the element has a width value of auto
(which is default), then the positioning properties can be used to size it. Just as left: 250px
means that the left side of the element should be 250px away from the viewport's left boundary, right: 0
means that its right side should be 0 (px, em, parsecs - unit doesn't matter for a value of 0) away from the vp's right boundary. Resize the viewport and this state will still be true.
more info: http://css-tricks.com/absolute-relative-fixed-positioining-how-do-they-differ/