关于元素定位:元素定位方法通常包括:position、float和z-index等。
对float的说明:div默认换行,当设置了元素向左或向右浮动时,则会向其父元素的左侧和右侧靠紧,当一行显示不开的时候会自动换行。样式可选值:left、right、none
注意:当设置float属性时,所有div一定要设置width,而height有时可以不设置,height会随着内容的变化,自动调整(IE6),其他浏览器不会变化,该属性在网页布局是非常重要的。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div1{width:500px;height:420px;border:20px solid teal;}
#div2{width:200px;height:100px;border:1px solid blue;background-color:yellow;
float:left;margin-left:40px;margin-top:20px;}
#div3{width:200px;height:100px;border:1px solid blue;background-color: yellow;
float:left;margin:20px 0px 0px 20px;}
#div4{width:200px;height:100px;border:1px solid blue;background-color: yellow;
float:left;margin:20px 0px 0px 40px;}
#div5{width:200px;height:100px;border:1px solid blue;background-color: yellow;
float:left;margin:20px 0px 0px 20px;}
</style>
</head>
<body>
<div id="div1">
<div id="div2">字块元素1</div>
<div id="div3">字块元素2</div>
<div id="div4">字块元素3</div>
<div id="div5">字块元素4</div>
</div>
</body>
</html>
当使用folat定位元素时,不同浏览器中对margin-left显示有差异,解决办法:display:inline;
div高度自适应问题:height:auto;overflow:hidden;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div1{width:500px;height:auto;overflow:hidden;border:20px solid gray;}
#div2{width:200px;height:200px;border:1px solid blue;float:left;margin-left:20px;
display:inline;background-color: yellow;}
#div3{width:200px;height:200px;border:1px solid blue;float:left;margin-left:20px;
display:inline;background-color: yellow;}
</style>
</head>
<body>
<div id="div1">
<div id="div2">字块元素1</div>
<div id="div3">字块元素2</div>
</div>
</body>
</html>
如何将子元素2强制换行?clear:both; Clear属性的使用:left 在左侧不允许有浮动元素,right 在右侧不允许有浮动元素,both 清除左右两侧的浮动影响,none 默认值,允许左右两侧浮动
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div1{width:800px;height:auto;overflow:hidden;border:20px solid gray;}
#div2{width:200px;height:200px;border:1px solid blue;float:left;margin-left:20px;
display:inline;background-color: yellow;}
#div3{width:200px;height:200px;border:1px solid blue;float:left;margin-left:20px;
display:inline;background-color: yellow;clear:both;}
</style>
</head>
<body>
<div id="div1">
<div id="div2">字块元素1</div>
<div id="div3">字块元素2</div>
</div>
</body>
</html>