所以我正在尝试纯 css 布局,但很快就卡住了。我有以下 html 和 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;
}
当我在 Chrome 中查看时,我得到了我期望的渲染:
但是,在 IE 中我得到以下信息:
请注意边栏左侧有一个巨大的空白区域。为什么在 IE 中显示?
最佳答案
出于同样的原因,我在 Safari 中遇到了同样的问题:你没有在 #header
中清除 float 。和 #header
不够高,无法容纳所有漂浮的 child 。
如果将页眉的高度增加到 31px,您应该(但可能不会)获得所需的布局。更好的方法是添加 overflow: hidden
作为一个明确的解决方案,这将使所有的 child #header
完全包含在 #header
中这将阻止他们干扰下一 block 的布局:
#header {
background-color: #151B54;
height: 30px;
width: 100%;
overflow: hidden;
}
实例:http://jsfiddle.net/ambiguous/EUmyN/
float 元素的经验法则是始终确保使用 overflow: hidden
清除它们在他们的容器上,或者,如果有必要,用明确的 <div style="clear: both;"></div>
在容器底部。
此外,当我们在这里时,您很少需要 width: 100%
在 block 元素上,例如 <div>
.如果你正在定位它或 float 它,那么你可能需要类似的东西但不是普通的 <div>
; block 元素默认为全宽。
关于css - 为什么我的基本 css 布局在 Internet Explorer 中呈现不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6887321/