注意:发生固定定位,绝对定位后,元素都变成了定位元素,默认高宽被内容撑开,则可以设置宽高;以下只针对绝对定位和固定定位的元素,不包括相对定位元素。
1.定位元素块的宽充满包含块
前提:定位元素的宽高未知
说明:定位元素的宽想要与包含块的宽一致,设置left,right等于0;定位元素的高想要与包含块的高一致,设置top,bottom等于零
1.1代码实现
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>定位元素的特殊的应用</title>
<style>
.outer{
width: 666px;
height: 200px;
background-color: pink;
position: relative;
}
.inner{
position: absolute;
border: 3px double red;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
text-align: center;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner">小黑子</div>
</div>
</body>
</html>
1.2图片实例
2.让定位元素在包含块中居中
注意: 定位的元素必须设置宽高
2.1代码实现(方法一)
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>定位元素的特殊的应用</title>
<style>
.outer{
width: 666px;
height: 200px;
background-color: pink;
position: relative;
}
.inner{
position: absolute;
border: 3px double red;
width: 300px;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
text-align: center;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner">小黑子</div>
</div>
</body>
</html>
2.2图片实例
2.3代码实现(不常用)
注意:一般开启了定位就不在用设置marin属性,因为不方便计算
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>定位元素的特殊的应用</title>
<style>
.outer{
width: 666px;
height: 200px;
background-color: pink;
position: relative;
}
.inner{
position: absolute;
border: 3px double red;
width: 300px;
height: 100px;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -50px;
text-align: center;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner">小黑子</div>
</div>
</body>
</html>