Notes from Codeschool CSS Cross Country Course - Level 5
Protecting Your Layout
Its important to create a layout that can handle changes without breaking.For example, here is a header, feature and body layout. Initially the margin is set on the .feature element like this:
![]() |
margins added to the feature section only |
margin: 20px 0 40px 0;
}
This will work fine unless you remove the .feature element. Because .feature declares the margins, it will break the layout if removed.
![]() |
margins no longer exist when feature section removed |
A better way to handle this is to apply a margin to all three sections:
.header {
margin: 20px 0 40px 0;
}
.feature {
margin: 20px 0;
}
.body {
margin: 10px 0;
}
This way, if the section is removed, it won't break the layout.
Margin Collapsing
When defining margins on subsequent items, you'll run into margin collapsing. The best way to describe what happens is through example.In the above example, you might expect the space between .header and .feature to be 60px, 40px bottom margin from .header plus 20px top margin from .feature. BUT, they are not additive in this way. Instead, CSS will choose the largest of the two margins and apply that. In this case 40px. That is called margin collapsing. As you can see, the space between .feature and .body works the same way.
![]() |
left side: margins are not additive. right side: the largest of the two margins wins out. |
Collapsing margins will not occur when one or more block elements has:
- padding or a border
- relative or absolute positioning
- a float of left or right
For more information on collapsing margins are they pertain to floats, read: http://www.w3.org/TR/CSS2/box.html#collapsing-margins
Specificity Problems
Its best to start out with base styles for most of your elements, then create more specific styles where you need them. For example, create a style called .featured, and define a base style for lists in case you or someone else needs another basic list..featured li { /* special case */
font-style: italic;
font-size: 14px;
color: #fff;
margin: 5px 0;
}
ul li { /* most other cases */
font-size: 12px;
margin: 3px 0;
}
No comments:
Post a Comment