CSS: Stop div and img from overlapping

usama8800 picture usama8800 · Jul 26, 2013 · Viewed 20k times · Source

I have a figure with an img inside it floating to the right and a div.
My html is

<div>
<figure id="fig">
<img src="img.jpg"></img>
<figcaption>Caption</figcaption>
</figure>
<div id="inner">
Blah Blah Blah
</div>
</div>

My div css is

#inner{
text-align: center;
width: 70%;
margin: auto;
padding: 1% 5%;
}

and my figure css is

#fig{
width:162px;
height:277px;
margin:auto 7px auto 7px;
float:right;
}

and my img css is

img{
width:162px;
height:277px;
}

My div is under the figure. The problem is that the div's width is 70% and if the figure comes in front of it, it doesnt know. I want the div to be 70% of the space - the figure.

Answer

hungerstar picture hungerstar · Jul 26, 2013

Remove the width from your #inner div and set a margin on the right of it that is the full width ( margin + padding + width + etc. ) of your figure. The figure will float into the right margin of #inner. Since DIVs are block level elements they take up 100% width by default.

http://jsfiddle.net/kacH7/

CSS

#fig {
     width: 162px;
     height: 277px;
     float: right;
     margin: auto 7px;
}
#inner {
     text-align: center;
     padding: 1% 5%;
     margin-right: 176px;
     background-color: red; /* demonstration only */
}
img {
     width: 162px;
     height: 277px;
}