So I am experimenting with pure css layouts, and immediately I have become stuck. I have the following html and css:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Layout</title>
<link type="text/css" href="site.css" rel="stylesheet" >
</head>
<body>
<div id="header">
<a href="#" id="logo">My Site</a>
<div id="search-area">
<form>
<input type="text" id="search-box" />
<input type="submit" value="Search" />
</form>
</div>
</div>
<div id="sidebar">
Account Name <br>
<a href="#">Edit My Account</a>
</div>
</body>
</html>
#header {
background-color: #151B54;
height: 30px;
width: 100%;
}
#logo {
position: relative;
left: 10px;
color: white;
font-size: x-large;
font-weight: bold;
text-decoration: none;
float: left;
margin-top: 3px;
}
#search-area {
position: absolute;
left: 200px;
margin-top: 3px;
}
#sidebar {
float: left;
width: 100px;
border-right: double;
}
When I view this in Chrome I get the rendering that I was expecting:
However, in IE I get the following:
Notice how there is a massive blank area to the left of the sidebar. Why is that showing in IE?
I get the same problem in Safari and for the same reason: you’re not clearing your floats in
#headerand#headerisn’t quite tall enough to contain all of its floated children.If you increase the height of the header to 31px, you should (but maybe not) get the desired layout. A better approach is you add
overflow: hiddenas a clear fix, that will make all of the children of#headerfully contained with#headerand that will stop them from interfering with the layout of the next piece:Live example: http://jsfiddle.net/ambiguous/EUmyN/
A rule of thumb with floated elements is to always make sure they’re cleared either with
overflow: hiddenon their container or, if necessary, with an explicit<div style="clear: both;"></div>at the bottom of the container.Also, while we’re here, you rarely need
width: 100%on a block element such as a<div>. If you’re positioning it or floating then maybe you’ll need something like that but not for a plain<div>; block elements are full width by default.