定位
基本
1.对于使用position:relative的子类元素而言,width:100%也始终是基于基父级元素而并不会基于其上层元素中的relative。
2.对于绝对定位的子无素,要是其外层的所有元素中都没有用position:relative,则width:100%是基于body,否则就是离基最近的一个position:relative的元素。
3.而对于position:fixed的元素,其一直是基于body,所以其宽度100%就是基于body。
position:relative;
left:100%;
是以父元素宽度为基础的百分比。如父元素宽度为:1000px,则设置了这个属性的元素就向左偏移1000px。
设置水平居中的技巧:
1.设置div的css属性:
text-align: center;
就这一行,不用设置宽度什么的,里面的
文字会自动居中。只能用于内容是文字的情况。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
<title>新建网页</title>
<style type="text/css">
body{
margin: 0;
padding: 0;
}
.wrap
{
background-color: yellow;
}
.inner
{
text-align: center;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="布尔教育 http://www.itbool.com" />
</head>
<body>
<div class="wrap">
<div class="inner">让这个div居中
</div>
</div>
</body>
</html>
2.margin:0 auto;
要设置自身宽度的(父元素的宽度也可以设置,不设置的话就继承父父元素的)。不然没用。自适应,要根据一个值来自适应。
<span style="white-space:pre"> </span>.wrap
{
width: 800px;
background-color: yellow;
}
.inner
{
width: 200px;
margin: 0 auto;
}
还有:
.wrap
{
float: left; /* 自适应内容宽度 */
position: relative;
left: 50%;
}
.inner
{
position: relative;
left: -50%;
}
<body>
<span style="white-space:pre"> </span><div class="wrap"><br>
<span style="white-space:pre"> </span><div class="inner">让这个div居中
<span style="white-space:pre"> </span></div>
<span style="white-space:pre"> </span></div>
</body>
即:若 body宽度为1366px,则wrap要偏移683px,距离之前位置的左边683px。所以wrap的左边界在body的中线上。
而由于wrap没有设置宽度,所以它的宽度=它子元素inner的宽度。
然后子元素设置距离以前位置的左边,偏移父元素wrap宽度(其实等于自身宽度)的1/2。所以就有了水平居中。