CSS中固定定位、相对定位、绝对定位以及flex布局高效定位
一、固定布局
将元素固定到一个位置,不管屏幕怎样移动,元素的位置不移动。
<style>
body {
height: 3000px;
background-color: lightskyblue;
}
.box{
width: 200px;
height: 340px;
background-color: pink;
/* 固定定位,将元素固定到一个位置,不管屏幕怎样移动,元素的位置不移动。 */
position: fixed;
/* 1.让元素定位到屏幕的右边垂直居中位置;
1.让元素整体走到屏幕的一半,50%;
2.让元素倒回去自身高度的一半,让盒子的中线到达居中位置;
*/
right: 0;
top: 50%;
margin-top: -170px;
}
</style>
<body>
<div class="box"></div>
</body>
效果图
二、相对定位、绝对定位
口诀:子绝父相
子元素绝对定位,父元素相对定位。
父元素设置相对定位,是为了给子元素指定参考物,子元素在父元素的范围里面运动。
<style>
.box1 {
/* ;
1.vw :视口(viewport)宽度(width);
2.vh :视口(viewport)高度(height);
2.50vw: 把视口宽度平均分成50份;假如现在屏幕宽度=1000px,平均分成50份,1vw=20px;
3. 若要设置与屏幕等宽等高,设置width:100vw;height:100vh;即可。
*/
width: 50vw;
height: 50vh;
background-color: pink;
/* 相对定位 */
position: relative;
}
.box2 {
width: 150px;
height: 150px;
background-color: lightskyblue;
/* 绝对定位 */
position:absolute;
/* 需求:让子盒子到达父盒子水平垂直居中位置 */
top: 50%;
left: 50%;
/*
translate(-50%,-50%)的作用是:往上、往左移动自身长宽的50%,使其居于中心位置;
*/
transform: translate(-50%,-50%);
}
</style>
<body>
<div class="box">
<div class="box1">
<div class="box2"></div>
</div>
</div>
</body>
效果图
三、flex布局
使用flex布局来实现水平垂直居中,效率更高、更简单。
<style>
.box {
width: 50vw;
height: 50vh;
background-color: pink;
/* 开启flex伸缩盒子布局 */
display: flex;
/* 让子元素水平方向居中 */
justify-content: center;
/* 让子元素垂直方向居中*/
align-items: center;
}
.box1 {
width: 100px;
height: 100px;
background-color: lightyellow;
}
</style>
<body>
<div class="box">
<div class="box1"></div>
</div>
</body>
效果图
最后,分享一个好玩的效果!可以在敲代码过程中产生一些动态效果!!
有兴趣的可以看看下边的文章!
https://blog.csdn.net/muzilanlan/article/details/81509374