laarsk
laarsk

Reputation: 872

CSS - prevent absolute positioned element from overflowing body

I have an element in a page which is absolute positioned using TOP and LEFT css styles. When it's positioned at a negative position in the left or top area, it's no problem. However, when the element is placed at a left position greater than the window innerwidth, scrollbars will appear.

Is there a way to somehow prevent this element from doing that? I can not set overflow:hidden; to my body element as that will destroy my layout. For example, a property like overflow-parent:none; would be great (but unfortunatly does not exist)

Upvotes: 12

Views: 22147

Answers (2)

yunzen
yunzen

Reputation: 33439

You have to work with nested divs which have all some different responsibility:
The outermost sets the position with left and right simultaniously. The right:0 sets it to the right.

The inner div is the real content div, which sets the width.

Here is a demo: http://jsfiddle.net/atnc3/44/

<div class="abs-position">
    <div class="abs-content">
         Absolut Vodka       
    </div>
</div>

.abs-position {
    position:absolute;
    right:0;
    left: 300px;
    overflow: hidden;
}
.abs-content {
    width: 400px;
}

.abs-position {
    position:absolute;
    right:0;
    left: 300px;
    overflow: hidden;
    /* following: just for demonstration purposes */
    padding: 5px;
    border: 1px solid gold;
    opacity: 0.8;
}
.abs-content {
    width: 400px;
    /* following: just for demonstration purposes */
    padding: 5px;
    background: lightgray;
}
.container {
    width: 600px;
    background: cornflowerblue;
}
<div class="abs-position">
    <div class="abs-content">
         Absolut Vodka       
    </div>
</div>
<div class="container">
Other content<br>
Other content<br>
Other content<br>
Other content<br>
</div>

Upvotes: 12

msponagle
msponagle

Reputation: 326

I thought absolutely positioned element did not take up space. Do you have a 'clear' in your element?

Try floating the element as a quick check? (float:left);

Upvotes: -3

Related Questions