欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

【CSS】定位元素居中显示

程序员文章站 2022-05-01 07:58:23
...

1、利用margin


p {
    width: 100px;
    height: 100px;
    background-color: skyblue;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;}


分析

  • top: 50%; left: 50%;让元素的左上在父元素中垂直水平居中

  • margin-top: -50px; margin-left: -50px;让元素向上向右偏移自身一半的距离

2、利用translate


p {
    width: 100px;
    height: 100px;
    background-color: skyblue;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);}


分析

  • top: 50%; left: 50%;让元素的左上在父元素中垂直水平居中

  • transform: translate(-50%, -50%);让元素向上向右移动自身一半的距离

3、四个方位全部为0,用margin定位


p {
    width: 100px;
    height: 100px;
    background-color: skyblue;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right : 0;
    margin: auto;}


分析

  • 四个方位全部为0时,相互抵消,盒子会在初始位置显示

  • margin: auto;让盒子垂直水平居中

更多【CSS】定位元素居中显示相关文章请关注PHP中文网!

相关标签: CSS