Friday, June 12, 2009

CSS Café Tutorial 16 - Floats within a Float



Remember the "#specials" div - the yellow colored block on the right above - that we floated in our document? Since then we added thumbnail images for each item in "#specials" and our div got longer. There's enough space to fit the image and description of each item side by side so I will float each thumbnail image either to left and right - the small red squares that are scattered around in the yellow div above. When an element is floated it's taken out of the flow but inline content will always flow around it so the descriptions will obey this rule and we will have everything lined up nicely.

.alignleft  { float: left; }
.alignright { float: right; }
#specials .alignleft { margin-right: 15px; margin-top: 5px;}
#specials .alignright { margin-left: 15px; margin-top: 5px;}
#specials h3 { margin: 0; }
#specials p { margin-bottom: 30px; }

Since .alignleft and .alignright are both generic sounding and have content that can be used by more than one element, I declared them on their own first. Then using descendant selectors, "#specials .alignleft" and "#specials .alignright", I added the margins necessary for each orientation. Bottom margin on "#specials p" is necessary to separate the different items. The descendant selector "#specials p" applies the rule only to those p's that are contained within the "#specials" div.

With the exception of orientation, XHTML structure is the same for all of the items in "#specials" div. If you want the thumbnail image to float to the left of the div you choose the "alignleft" class, for floating to the right, it's "alignright". We had the XHTML all ready from previous tutorials so just need to add the class that'll do the floating to the img tag.

<img class="alignleft" src="http://pics.cssrule.com/pics/d.jpg" alt=" ">
<h3>86 Percent Donut</h3>
<p>Glazed with a bittersweet chocolate that is 86% pure cocoa beans....</p>


A comparison screenshot:


The document in full resolution.

Post a Comment

Note: Only a member of this blog may post a comment.