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样式
  • 怎么在印象笔记中修改默认笔记标题字体
  • 热门搜索
    腿酸是怎么回事 烤箱怎么做蛋糕 小孩肚子胀气怎么办 舌苔发黑是怎么治疗 附件囊肿怎么治疗 长虹电视怎么样 怎么养鱼 头晕目眩怎么办 二代火影怎么死的 婧字怎么读