2021/3/24–前端第13天–定位
定位
脱离文档流三种方法:浮动、绝对定位、固定定位
position:
relative 相对定位:相对于元素原有位置的定位
不受其他元素影响,改变位置但不脱离标准文档流。
占了一个坑,但是人不在这
向中心偏移为正,向边缘偏移为负
<!-- 设置样式 -->
<style>
div {
width: 100px;
height: 100px;
background: pink;
font-size: 50px;
color: rgb(4, 131, 4);
border: 1px solid #000;
}
.class2 {
/* 浮动后后面元素挤上来了 */
/* float: left; */
/* margin-left: 200px; */
/* 不希望影响兄弟元素相对位置,使用相对定位 */
position: relative;
/* top: 100px;
left: 200px; */
/* bottom: -200px;
right: 50px; */
}
span {
padding: 12px;
background: url("../../pic/test.jpg") no-repeat;
font-size: 0;
/* vertical-align: middle; */
/* 用相对定位解决对齐 */
position: relative;
top: -7px;
}
strong {
font-size: 14px;
font-weight: normal;
/* vertical-align: text-top; */
position: relative;
top: -20px;
left: 10px;
margin-right: 15px;
}
</style>
</head>
<body>
<div class="class1">1</div>
<div class="class2">2</div>
<div class="class3">3</div>
<div class="class4">4</div>
<!-- 设置列表 -->
<ul>
<li><span></span>标题</li>
</ul>
<h1>爱创课堂<strong>100</strong>课堂</h1>
</body>
absolute 绝对定位:
默认以body为基准,脱离文档流
特殊:bottom是相对于屏幕的底边,而不是body的底边。
嵌套盒子寻找离自己最近的设置了定位的祖先元素进行定位。
从padding开始,设置border会影响定位结果。
设置绝对定位,display属性失效
<style>
.container {
margin: 100px;
padding: 100px;
width: 400px;
height: 400px;
background-color: pink;
border: 20px solid #ccc;
position: absolute;
}
.box {
width: 100px;
height: 100px;
background-color: green;
position: absolute;
/* 默认相对于body , 父元素设置定位后根据父元素 */
top: 100px;
left: 100px;
}
/* 行内元素设hi绝对定位 */
.box2 {
width: 100px;
height: 100px;
background: greenyellow;
/* span给了绝对定位后宽高就显示出来了,绝对定位不区分行内还是块元素 display失效*/
position: absolute;
top: 150px;
left: 150px;
}
.box3 {
width: 500px;
height: 400px;
background: skyblue;
/* 居中 让盒子中心点在最中间*/
position: absolute;
left: 50%;
top: 50%;
/* 通过margin移动盒子 margin相对于绝对定位后的位置*/
margin-top: -250px;
margin-left: -250px;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
<span class="box2"></span>
</div>
<div class="box3"></div>
</body>
fixed 固定定位:
1、相对于浏览器窗口的定位,和父元素无关。
2、脱离文档流(IE6不支持,通过absolute模拟)
3、不论是块还是行内元素,一旦固定定位,都可以设置宽高。
4、display失效
5、可以通过偏移量设置宽高
6、优先级 left 、 top
7、偏移量一旦设置了负值,
<style>
.container {
width: 400px;
height: 800px;
margin: 100px;
padding: 100px;
border: 10px solid #ccc;
background-color: pink;
}
.box {
/* width: 100px; */
height: 100px;
background-color: green;
/* 固定定位 */
position: fixed;
/* 设置负值,将会移出窗口 */
/* 更改盒子大小 */
top: 0px;
left: 100px;
right: 100px;
/* bottom: 100px; */
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
<h1>hello</h1>
</body>
static 静态(默认)移出窗口看不到。
inherit 规定应该从父元素继承 position 属性的值。