Rabu, 01 Februari 2012

How to Make a Half Element Keep Fluid Above the Fixed Width Element

One day I accidentally discovered this technique when I was trying to answer the question in a forum. Maybe this will be a little bit of knowledge for you about layout. The problem is: How do we keep an element with a half position of the page size keep fluid/expandable while the page is not.
Say that we want to make a layout with centered fixed width page and a ribbon above it. But, we want the ribbon placed by half of the page and we want this ribbon keep expandable without make the HTML page overflowed:



First, you should understand that the ribbon element is not a child element of the page. It is the element that is placed on the bottom of the page with absolute position:
<div id="outer">
<div id="page-wrap">
<!-- content here -->
</div>
<div id="half-ribbon">
<div class="inner">Lorem Ipsum</div>
</div>
</div>

Then, set the CSS to absolute position for the ribbon and centered horizontally for the page:
#outer {
width:100%;
position:relative;
}

/* Center horizontally */
#page-wrap {
width:370px;
height:1000px;
background-color:pink;
margin:0px auto 0px;
}

#half-ribbon {
position:absolute;
top:30px;
left:50%;
width:50%;
background-color:black;
}

/* CSS Box-Model: Padding will distort the value of 'width:50%' on #half-ribbon element,
I should add an extra element in it so you can set the value of padding without affecting the parent element */
#half-ribbon .inner {
text-align:left;
padding:10px 15px;
color:white;
font:bold 14px Georgia,Serif;
}
Note: Rather than write the right value by 0px, I would prefer to write down the left by 50%.
For unknown reasons, Chrome has an inconsistent interpretation about right and bottom position.

Here I also add an outer <div id="outer"></div>. It just to ensure that you can place this layout on everywhere you want. Of course, you can use the window itself as the outer:
/* Center horizontally */
#page-wrap {
width:370px;
height:1000px;
background-color:pink;
margin:0px auto 0px;
}

#half-ribbon {
position:absolute;
top:30px;
left:50%;
width:50%;
background-color:black;
}

#half-ribbon .inner {
text-align:left;
padding:10px 15px;
color:white;
font:bold 14px Georgia,Serif;
}

But that's only work for the element that placed on the whole page as a main layout.

Here I have a Fiddle for you: View Demo on JSFiddle

0 komentar:

Posting Komentar