css绝对定位 (position)

                                                              css绝对定位    (position)

一、css绝对定位遇到的问题?

1)设置了position:absolute的元素都会变成inline-block元素。

2)绝对定位是相对最近的 有定位的 祖先元素进行定位,若没有 有定位的 祖先元素则相对document(文档)定位。

3)  绝对定位是脱离原来的位置进行定位,会产生层级(层级提升,可以通过z-index属性设置元素的层级)

      也就是说:

    (1)如果父级的盒子是靠其子元素撑起来的,一旦子元素设置了position:absolute,那么父元素将不能被子元素撑起。

      (2)如果设置绝对定位的元素有兄弟元素,且兄弟元素在其后面那么其兄弟元素将上升。

二、绝对定位的应用

1、 元素水平竖直居中(方法一)

<html>

<head>

<meta charset="utf-8">

<title>元素水平竖直居中的第一种方法</title>

<style>

*{

margin:0;

padding:0px;

}

html,body{

height:100%;

}

.wrapper{

height:100%;

position:relative;

}

.wrapper .box{

position:absolute;

top:0;

left:0;

right:0;

bottom:0;

width:200px;

height:200px;

margin:auto;

background:pink;

}

</style>

</head>

<body>

<div class="wrapper">

<div class="box"></div>

</div>

</body>

</html>

2、元素水平竖直居中(方法二)

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>元素水平竖直居中的第二种方法</title>

<style>

*{

margin:0;

padding:0;

}

html,body{

height:100%;

}

.wrapper{

height:100%;

position:relative;

}

.wrapper .box{

position:absolute;

left:50%;

top:50%;

margin-left:-100px;

margin-top:-100px;

height:200px;

width:200px;

background:pink;

}

</style>

</head>

<body>

<div class="wrapper">

<div class="box"></div>

</div>

</body>

</html>

3、绝对定位模拟固定定位

<html>

<head>

<meta charset="utf-8">

<title>绝对定位模拟固定定位</title>

<style>

*{

margin: 0;

padding: 0;

}

html,body{

height:100%;

overflow:hidden;

}

.wrapper{

overflow:auto;

height:100%;

border:2px solid red;

}

.wrapper>.box{

    position:absolute;

left:0;

top:0;

width:200px;

height:200px;

 

}

.inner{

    height:2000px;

}

</style>

</head>

<body>

<div class="wrapper">

<div class="box"></div>

<div class="inner">

</div>

</div>

</body>

</html>

 

posted on 2019-06-03 17:12  李二狗子  阅读(463)  评论(0)    收藏  举报

导航