Border around HTML Faux Columns
I am working on a webapp and I want to put borders around floating divs which I call faux columns for lack of a better description. I know this is very very basic but for some reason - incompetence maybe - I cannot get this to work
The procedure: I float two divs left and right. These divs are nested in another div which I want to put a border around.
The code:
<html>
<head>
<meta http-equiv="Content-type" conten开发者_开发百科t="text/html; charset=utf-8">
<title>StackOvervlow</title>
<style type="text/css" media="screen">
body {
width: 900px;
}
#wrapper {
border: 2px solid gray;
}
#container {
width: 600px;
float: left;
background-color:#678;
}
#sidebar {
width: 200px;
float: right;
background-color: bisque;
}
#footer {
clear: both;
text-align: center;
}
</style>
</head>
<body>
<div id="header"></div>
<div id="wrapper">
<div id="container">
<p>Placeholder Text.</p>
<p>Placeholder Text.</p>
</div>
<div id="sidebar">
<p>Placeholder Text.</p>
</div>
</div>
<div id="footer">
<p>Some footer stuffs</p>
</div>
</body>
</html>
The outcome...
Please explain why the border shows up as a line and does not go around the two enclosed divs as expected. If you could suggest ways to fix this, I'll appreciate that.
Thank you.
Simply add:
overflow: hidden;
to the CSS for #wrapper
, demo at: JS Fiddle.
The reason the border collapses to a line is because the floated elements are removed from the document's flow, which means that they essentially occupy no space within their parent element, which, with no contents, collapses. The overflow: hidden;
causes the parent element to wrap around its children. Though, to be honest, I don't particularly understand why that happens.
It's worth having a read of CSS Floats 101, at A List Apart for a refresher/primer on CSS floats, though, for pointers on their behaviour.
When you float the element, it does not take up space the same way as it does when it is inline.
The solution is to put a block level element that has clear both attribute at the bottom:
<div style='clear:both;'></div>
See detail here: http://jsfiddle.net/billymoon/eDqg5/
精彩评论