html fixed元素的水平和垂直居中

2025-11-05 15:38:31

1、定义html界面

<html>

    <head>

        <title>fixed 水平居中 demo</title>

    </head>

    <body>

        <div class="fixed"></div>

    </body>

</html>

2、设置css样式

.fixed{

    position: fixed;

    width: 100px;

    height: 100px;

    /* top 坐标居中 */

    top: 50%; 

    /* left 坐标居中 */

    left: 50%; 

    /* 由于元素的高度是100px 所以此处设置为-50px以达到整个元素上移自己高度的一半,达到垂直居中 */

    margin-top: -50px; 

    /* 由于元素的高度是100px 所以此处设置为-50px以达到整个元素左移自己宽度的一半,达到水平居中 */

    margin-left: -50px; 

    border: solid 1px #c5c5c5;

    border-radius: 5px;

    background-color: blueviolet;

}

3、整个页面内容如下:

<html>

    <head>

        <title>fixed 水平居中 demo</title>

        <style>

            .fixed{

                position: fixed;

                width: 100px;

                height: 100px;

                /* top 坐标居中 */

                top: 50%; 

                /* left 坐标居中 */

                left: 50%; 

                /* 由于元素的高度是100px 所以此处设置为-50px以达到整个元素上移自己高度的一半,达到垂直居中 */

                margin-top: -50px; 

                /* 由于元素的高度是100px 所以此处设置为-50px以达到整个元素左移自己宽度的一半,达到水平居中 */

                margin-left: -50px; 

                border: solid 1px #c5c5c5;

                border-radius: 5px;

                background-color: blueviolet;

            }

        </style>

    </head>

    <body>

        <div class="fixed"></div>

    </body>

</html>

4、最终显示效果

html fixed元素的水平和垂直居中

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢