CSS coding delivers more “WTF moments” than any other work activity I engage in these days. I need to understand it better, specifically CSS margins and floats. Made some time today to study up.
I read and re-read the articles below. They are aging but speak to a time when the evil IE6 was even more prominent than it is years later in 2009.
General insights include:
- Kill IE’s double margin bug with
display:inlineon a floated items. - When 2 adjacent elements’ margins meet, only the bigger margin is used.
- If an item’s 2 opposite margins meet, they both go away (self-collapse)
- Nested items without padding or border will cause the top and bottom margins of all to collapse. Left and right margins remain. Adding padding or border makes the margin come back.
- Set
overflow:hiddenon columns to prevent object blow out in IE. - To make columns,
float:lefton one andfloat:righton the other. - Self clear an object (always clear floats) with the
:afterfilter. (Example below.) - Center an item by setting
autoon left and right margins.margin:0 auto. - In addition to auto margins, to center an item in IE, also use
text-align:centeron parent, then reset text-align in child, usuallytext-align:left.
.columns:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
Convert a list into a horizontal menu
Using background images instead of text. Fixed width, left margins, using negative margin on UL to cancel first margin.
<ul class="menu">
<li><a href="#somewhere1" id="link1"><em>link 1</em></a></li>
<li><a href="#somewhere2" id="link2"><em>link 2</em></a></li>
<li><a href="#somewhere3" id="link3"><em>link 3</em></a></li>
</ul>
ul.menu {
margin:0 0 0 -20px;
float:left;
width:100%;
}
ul.menu li {
list-style-type:none;
display:inline;
float:left;
margin:0 0 0 20px;
}
ul.menu li a {
display:block;
height:50px;
background-color: #0f0;
}
ul.menu li a em {
display:none;
}
ul.menu li a#link1 {
width:100px;
background-image: url(link1.png);
}
ul.menu li a#link1:hover {
background-image: url(link1-over.png);
}
ul.menu li a#link2 {
width:110px;
background-image: url(link2.png);
}
ul.menu li a#link2:hover {
background-image: url(link2-over.png);
}
ul.menu li a#link3 {
width:120px;
background-image: url(link3.png);
}
ul.menu li a#link3:hover {
background-image: url(link3-over.png);
}