spraff
spraff

Reputation: 33395

CSS create layers without using position:absolute (make container big enough for all layers)

Please see this snippet. UPDATE: answer looks like this.

Here I want the #container element to be big enough to contain the #sometimes_shown layer, but it gets its size from the #always_shown child only.

position:absolute removes #sometimes_shown from the flow, and this aspect of the standard gets mentioned when other people have similar problems.

My question is: can I create the same layer effect without using position:absolute, thereby including the size of all child layers in the parent's flow logic?

Precomputed widths/heights/offsets are not an option: this has to flow dynamically. I won't accept any solution which contains a dimensioned number other than zero. CSS-only solutions are strongly preferred, compatibility with old browsers is not a priority, jQuery/javascript solutions are a last resort. Thanks.

Upvotes: 1

Views: 728

Answers (1)

web-tiki
web-tiki

Reputation: 103780

You can use floats.

Fiddle (I deleted all your margins for the test)

This solution needs some html markup changes and you will have to use margin-left: -100%; on #sometimes_shown .

How it works :

  • put both divs in a wrapper with width:50%; and float:left; so both elements are on the same line.
  • get the elements with back to normal width adding width:200%; to #always_shown and #sometimes_shown
  • Add margin-left: -100%; to #sometimes_shown so it stacks to the left of container
  • add a dummy div with clear:both; at the bottom of the container so it wraps around the floated elements

Here is the code:

HTML :

<div id="container">
    <div class="wrap">
        <div id="always_shown">
            <p>I am always here 1. I am always here 2. I am always here 3. I am always here 4. I am always here 5. I am always here 6. I am always here 7.</p>
        </div>
    </div>

    <div class="wrap">
        <div id="sometimes_shown">
            <p>I am sometimes here</p>
             <p>Extra 1</p>
             <p>Extra 2</p>
             <p>Extra 3</p>
             <p>Extra 4</p>
        </div>
    </div>
    <div class="clr"></div>
</div>

CSS :

#container
{
    border: thin solid black;
}

#always_shown
{
    width: 200%; 
    color: red;
}

#sometimes_shown
{
    width: 200%; 
    margin-left: -100%;
    color: green;
}
.wrap{
    float:left;
    width:50%;
}

.clr{
    clear:both;
}

Upvotes: 1

Related Questions