定位position
相对定位:
相对于自己原来的位置进行偏移
position:relative;
top:-20px;/*往上移*/
left:20px;/*往右移*/
#first{
border: 1px dashed red;
background: #FF0000;
position: relative;
top: -20px;/*距离顶部-20px,插进去20px,也就是向上移动20px*/
left: -20px;/*距离左边-20,向右移动20px*/
}
#second{
border: 1px dashed green;
background: green;
}
#third{
border: 1px dashed yellow;
background: yellow;
position: relative;
bottom: -10px;/*向下移动-10*/
}
</style>
</head>
<body>
<div class="father">
<div id="first">第一个盒子</div>
<div id="second">第二个盒子</div>
<div id="third">第三个盒子</div>
</div>
相对于原来的位置进行指定的偏移 。相对定位的话,仍然在标准文档流中,原来的位置会被保留。
练习
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FTkpqjD4-1610839005642)(C:\Users\ThinkPad\Desktop\截图\练习截图.png)]
.father{
width: 300px;
height: 300px;
border: 2px solid red;
margin: 0 auto;
padding: 10px;
}
a{
width: 100px;
height: 100px;
background: pink;
text-decoration: none;
line-height: 100px;
text-align: center;
color: white;
display: block;
}
.a2,.a4{
position: relative;
left: 200px;
top: -100px;
}
.a5{
position: relative;
left: 100px;
top: -300px;
}
a:hover{
background-color: #6284FF;
}
</style>
</head>
<body>
<div class="father">
<a class="a1" href="">链接1</a>
<a class="a2" href="">链接2</a>
<a class="a3" href="">链接3</a>
<a class="a4" href="">链接4</a>
<a class="a5" href="">链接5</a>
</body>
出现的问题
- 文字在块内居中:
height: 100px;
text-align: center;/*水平居中*/
line-height: 100px;/*行高等于块高,竖直居中*/
- 行内元素a内不能嵌套块元素div
绝对定位
position:absolute;
left:100px;
定位:基于xx定位
- 没有父级元素定位的前提下,相对于浏览器的边框
- 假设父级元素存在定位,我们通常会相对父级元素进行偏移
- 在父级元素范围内移动,为负值时不会超出父级范围
相对于父级或者浏览器的位置,进行指定的偏移,绝对定位的话,它不在标准文档流中,原来的位置不会被保留。
固定定位
position:fixed;
right:0;
bottom:0;
body{
width: 1000px;
height: 1000px;
}
div:nth-of-type(1){
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
right: 0;
bottom: 0;
}
div:nth-of-type(2){
width: 50px;
height: 50px;
background-color: yellow;
position: fixed;
right: 0;
bottom: 0;
}
<body>
<div></div>
<div></div>
</body>
z-index及透明度
图层
z-index默认为0.
先通过给父级 position:relative
然后下面的子元素通过 position:absolute 浮起来,才能设定层级
.bg{
z-index:0-999;/*设置层级 0为最后面一层 999最前mian*/
opacity:0.5;/*背景透明度*/
}
div{
margin: 0;
padding: 0;
border: 2px solid red;
width: 300px;
font-size: 12px;
line-height: 25px;
}
ul{
padding: 0px;
margin: 0px;
list-style: none;
position: relative;
}
.text,.bg{
position: absolute;
width: 300px;
height: 25px;
top: 178px;
color: #FFFFFF;
}
.text{
z-index: 1;
}
.bg{
background: #0a0202;
opacity: 0.5;
}
出现的问题:text和bg绝对定位之后,要设定一下高度,才能显示出空li
0层的优先级最小,排在最底层,默认为0
透明度opancity