定位
css中的position属性即为定位,默认值为static,常用的属性值有三个,分别为relative(相对定位),absolute(绝对定位),fixed(固定定位),定位之后,要设置宽度,否则宽度将由内容决定。
相对定位
当position的属性值为relative则为相对定位
1、相对定位是相对于自身原有的位置进行定位的。
2、可以通过left、right、top、bottom四个属性来控制元素四方向的位置值。
3、元素相对定位之后,原来的位置保持不变。
4、元素相对定位之后,对其他的元素位置不会有影响,只会覆盖其他元素。
5、当left和right一起书写时,元素的位置由left决定
6、当top和bottom一起书写时,元素的位置由top
已下是关于相对定位的一个小练习,提供大家参考:
<style>
div{
width: 100px;
height: 100px;
margin: 10px;
}
.box1{
background-color: #B61420;
position: relative;
left: 0px;
top: 0px;
bottom: 0px;
right: 0px;
}
.box2{
background-color: #005ea7;
}
</style>
</head>
<body>
<div class="box1">
</div>
<div class="box2"></div>
</body>
绝对定位
当position的值为absolute时,则为绝对定位
1、绝对定位的原理则为相对于最近定位父级的元素进行定位,也就是说绝对定位需要参照物,且父级position的值不能为static(当它的父级没有定义定位时,则元素会往外继续寻找定位的父级或祖宗元素,如果都没有,则参照根元素(html标签)进行绝对定位)。
2、绝对定位与相对定位一样,通过left、right、top、bottom四个属性来控制元素的位置。
3、绝对定位的元素脱离页面流,原来的位置不再保留,但是定位的元素不会挤到其他元素,因为脱离了文档流。
4、父级的定位属性值可以是相对定位页可以是绝对定位,但是如果不想要影响到父级的位置,或者不想要父级脱离页面流,则父级的position值则应为相对定位(position:relative)。
以下时关于绝对定位的一个小例子,可供参考
<style>
.outer{
width: 500px;
margin: 100px auto;
border:1px solid #000;
position: absolute;
}
.outer .box1{
width: 200px;
height: 200px;
background-color: #005ea7;
position: absolute;
left: 10px;
top: 10px;
}
.outer .box2{
width: 270px;
height: 100px;
background-color: #B61420;
}
</style>
</head>
<body>
<div class="outer">
<div class="box1">
</div>
<div class="box2">
</div>
</div>
</body>
固定定位
当position的值为fixed则为固定定位,相对于浏览器窗口定位,不需要参照物,也就是说和定义固定定位与其他元素没有任何的关系。
伪元素
伪元素有四种,分别为:
1、:frist-letter:向文本的第一个字母添加特殊样式;
2、:frist-line:向文本的首行添加特殊样式;
3、:before,将会在选中的元素之前添加一个元素;
4、:after:将会在选中的元素之后添加一个元素。
其中:before和:after是我们比较常用的伪元素,在伪元素当中添加内容可以使用content属性。
以下是关于伪元素使用的一个小例子,可供参考:
<style>
p{
width: 300px;
height: 40px;
line-height: 40px;
background-color: #ccc;
}
p:before{
content: "\200B";
display: inline-block;
width: 21px;
height: 40px;
background: url("../images/index.png") center center no-repeat;
}
p:after{
content: "\200B";
display: inline-block;
width: 21px;
height: 40px;
background: url("../images/index.png") center center no-repeat;
margin-left: 100px;
}
</style>
</head>
<body>
<p>我是伪元素</p>
</body>
a标签的伪类
1、:link,当a标签拥有链接属性时控制的,初始状态时的显示状态
2、:visited,当链接被访问过的状态
3、:hover,当鼠标悬停在标签上时的状态
4、:active,当鼠标按下时的状态
以下是关于伪元素使用的一个小例子,可供参考:
<style>
.a1{
/*color: pink;*/
}
a:link{
color: greenyellow;
}
a:visited{
color: red;
}
a:hover{
color: deepskyblue;
font-size: 100px;
}
a:active{
color: blue;
}
</style>
</head>
<body>
<a class="a1" href="#####">111</a>
<a>222</a>
</body>