user1355300
user1355300

Reputation: 4987

expanding div width if other div is missing

I have two divs inside a containers floating to the left. In some of the containers the left div is missing, so I want to do it so that if the left div is missing then the right div should expand to the full width of container.

In my code below, I have specified the width of the right div and because of this if the left div is missing, it does not fill the whole container.

Here's the code:

HTML:

<div class="box">
    <div class="left"><img src="http://i50.tinypic.com/2cxj31z.jpg" ></div>
    <div class="right">... content...</div>
</div>

CSS:

.box{
    width: 300px;    
    border: 1px solid red;
    margin: 0 auto;
    overflow: hidden;
}

.left{
    width: 80px;
    margin-right: 10px;
    float: left;
}

.right{
    float: left;
    width: 210px;
}

JSFiddle: http://jsfiddle.net/DMFz8/

Upvotes: 0

Views: 165

Answers (2)

Giona
Giona

Reputation: 21114

You can use an adjacent selector, so that .right becomes floated only if there's a .left next to it.

Replace the .right selector and rule with this:

.left + .right{
    float: right;
    width: 210px;
}

Demo

Upvotes: 4

Afshin
Afshin

Reputation: 4215

I don't know what ypu want exactly but try this maybe helpful

<div class="box">
 <div class="left"><img src="http://i50.tinypic.com/2cxj31z.jpg" ></div>
   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eget ligula sapien, sed tempor felis. Vivamus eget bibendum augue. Sed sit amet nulla lectus. Etiam vitae lacus ipsum. Aliquam malesuada orci nec ipsum pretium fermentum. Fusce libero mauris, convallis ut aliquam et, scelerisque vel turpis. 
</div>

jsFiddle

Upvotes: 1

Related Questions