前端——CSS定位

定位:

  • 默认为静态定位
  • 投标现象
  • 压盖现象
  • 层级比标准文档高

position

  • static  静态
  • relative    相对
  • absolute    绝对
  • fixed    固定

relative(相对定位)

.st{
    width: 100px;
    height: 100px;
    position: relative;
}
  • 与标准文档流下的盒子没有任何区别
  • top|bottom|left|right来进行对元素的微调
  • 做“子绝父相”布局方案的参考
  • 以原来的盒子作为参考点

absolute(绝对定位)

.st{
    width: 100px;
    height: 100px;
    position: absolute;
}
  • 如果单独设置一个盒子为绝对以top描述定位它的参考点,是以body的(0.0)为参考点。
  • 以bottom描述,它的参考点是以浏览器的左下角为参考点
  • 如果有父元素设置了相对定位,那么会以父元素进行定位,而不是body了。这就是子绝父相

让绝对定位的盒子垂直居中:

1. 子绝父相以后,默认情况下,子盒子会给自己增加一个position的参数,让其靠在父盒子左上角。

如果想让其居中,水平对齐,那么就需要把position的力取消掉,同时将margin设置为auto

margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;

2. 使用百分比的方式,将子盒子移位至相应位置中。

  • child中的left和top是指父盒子中的50%
  • margin-top和margin-left是指的子盒子
  • 设置完成后,父盒子更改,不会影响水平居中效果。
.father{
    width: 200px;
    height: 200px;
    background-color: #000000;
    position: relative;

}
.child{
    width:100px;
    height: 100px;
    background-color: green;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-top: -50px;
    margin-left: -50px;
}

 

posted @ 2022-09-27 08:58  新兵蛋Z  阅读(57)  评论(0)    收藏  举报