Radovan
Radovan

Reputation: 23

Layout with relative positioning

I want to make this layout:

https://i.sstatic.net/uhgMg.jpg

#container
{
width:600px;
background:blue;
margin:0 auto;
}

.box
{
float:left;
width:196px;
height:318px;
background:red;
}

#box1
{
position:relative;
left:-140px;
float:left;
}

#box2
{
position:relative;
left:-102px;
}

#box3
{
position:relative;
left:-66px;
}

#box4 //this div is doing the mess because it's default position is under the other 3 divs and that's why the container stretches.
{
position:relative;
left:558px;
top:-318px;
}

<div id="container">

<div>RANDOM CONTENT</div>

<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
<div class="box" id="box3"></div>
<div class="box" id="box4"></div>

<div style="clear:both"></div>
</div>

There are 4 relative positioned divs next to each other in some container.

The red line in my picture shows where the container's height should end but it doesn't because of the last div which default position is down there. I can't set fixed height for container because of random stuff above.

How to do it?

Upvotes: 1

Views: 114

Answers (2)

Subdigger
Subdigger

Reputation: 2193

why not to divide into 3 sections

<div id="container">

<div class="cont">RANDOM CONTENT</div>
<div class="banner">
  <div class="box" id="box1"></div>
  <div class="box" id="box2"></div>
  <div class="box" id="box3"></div>
  <div class="box" id="box4"></div>
</div>
<div style="clear:both"></div>
<div class="cont">RANDOM CONTENT</div>
</div>

and css

.banner {
    height: 318px;
    width: 800px;
    position: relative;
}
.cont {
width:600px;
background:blue;
margin:0 auto;
}

Upvotes: 0

Dave
Dave

Reputation: 29121

Create divs that don't have widths that add up to more than the width of their containing element. In this example, your containing div is 600 pixels wide, but you have 784 pixels worth of elements you're trying to float in. If you change them to 148px instead of 198px you should be good.

Though - I'm not sure why you're using float AND relative positioning. Relative positioning positions something relative to where it would normally flow in the document... I would probably just stick with float:left; - there shouldn't be a need for relative positioning.

Or, if you want them to be positioned like that regardless of the width of their containing element, just use absolute positioning and drop float and relative altogether.

Upvotes: 1

Related Questions