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

 时间:2026-02-13 06:16:07

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元素的水平和垂直居中

  • vsco怎么取消自动续费
  • 蔬菜生吃好还是熟吃好?
  • 天地劫手游召祐魂石选择攻略
  • jquery如何通过id定义元素的css样式
  • 怎么在印象笔记中修改默认笔记标题字体
  • 热门搜索
    灯谜大全 大鹅的做法大全 便宜手机大全 肚胀是怎么回事 怎么查苹果手机序列号 刀郎歌曲大全 星座性格分析大全 眼睛刺痛是怎么回事 汉堡包用英语怎么写 蛤蚧怎么吃