joemillervi
joemillervi

Reputation: 1067

Centered div, with divs on either side that extend to page margin

I want a centered div, with divs on either side that extend to page margin. There has to be a more efficient way of doing this.

Currently I have two divs, each with 49% width and then under them a centered div that I moved on top of them to create the effect.

Problem is, this creates an awkward space below.

HTML:    
<div id="green"></div>
<div id="red"></div>
<div id="blue"></div>

CSS:
#green {
height:25em;
width:49.99%;
background-color:#132a10;
display:inline-block;
margin:0;
float:left;
opacity:.47;
}
#red {
height:25em;
width:49%;
background-color:#400120;
display:inline-block;
margin:0;
opacity:.4;
}
#blue {
background-color:#436a97;
position:relative;
bottom:26em;
width:22em;
height:27em;
margin-right:auto;
margin-left:auto;
z-index:1;
opacity:;
}

http://jsfiddle.net/JFA2z/5/

Upvotes: 0

Views: 98

Answers (2)

sanepete
sanepete

Reputation: 1128

Make all your divs the same height and give the blue div a top margin of -16px

<html>
<head>
<style>
#green
{
 height:7em;
 width:49.99%;
 background-color:#132a10;
 display:inline-block;
 margin:0;
 float:left;
 opacity:.47;
}
#red
{
 height:7em;
 width:49%;
 background-color:#400120;
 display:inline-block;
 margin:0;
 opacity:.4;
}
#blue
{
 background-color:#436a97;
 position:relative;
 bottom:6em;
 width:6em;
 height:7em;  /*edit*/
 margin-right:auto;
 margin-left:auto;
 margin-top:-16px;  /*edit*/
 z-index:1;
 opacity:;
}
</style>
</head>
<body>
  <div id="green"></div>
  <div id="red"></div>
  <div id="blue"></div>
</body>
</html>

Upvotes: 0

j08691
j08691

Reputation: 207923

That gap comes from using relative positioning on the blue div. With relative positioning the element's original position still takes up space, and the element is re-positioned relative to it. You can use absolute positioning instead, along with these rules, to fix it:

#blue {
    background-color:#436a97;
    position:absolute;
    width:6em;
    height:7em;
    margin:auto;
    top:0;
    left:0;
    right:0;
}

jsFiddle example

Upvotes: 2

Related Questions