html+css实现元素在浏览器居中

实现元素在浏览器居中

1、已知元素的宽高大小

  • 给固定定位,左边与上边方向50%,再给元素margin(外边距)左和上自身宽高的一般负值

  • width: 300px;height: 400px;position: fixed;left: 50%;top: 50%;margin-left: -150px;margin-top: -200px;

<style>
        div{
            width: 300px;
            height: 400px;
            border: 1px solid #000;
            position: fixed;
            left: 50%;
            top: 50%;
            margin-left: -150px;
            margin-top: -200px 

        }
    </style>

<body>
    <div></div>
</body>

2、未知元素的宽高大小

  • 给固定定位,四个方向为0,margin为auto

  • position: fixed;top: 0;right: 0;bottom: 0;left: 0;margin: auto;

   <style>
        div{
            width: 300px;
            height: 400px;
            border: 1px solid #000;
            position: fixed;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            margin: auto

        }
    </style>
<body>
    <div></div>
</body>

 


版权声明:本文为Wjc_1hh原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。