html-如何让背景宽高100%元素上下左右居中

在一些登陆,注册页面中经常会出现这种布局模式,背景图片或者背景颜色宽度,高度100%铺开;

中间添加div上下左右居中,今天就带着大家做这样一个效果

 

 

<style>
        body,p,h1{
            padding: 0;
            margin: 0;
        }
        html,body{
            height: 100%;
            width: 100%;
        }
        html{
            height: 100%;
            width: 100%;
        }
        .div1{
            width: 100%;
            height: 100%;
            background-color: teal;
        }
        .div2{
            position: fixed;
            width: 300px;
            height: 400px;
            margin: auto;
            background-color: tomato;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
        }
    </style>
<body>
    <div class="div1">
        <p class="div2">居中元素</p>
    </div>
</body>

 

其中position: fixed;是必须要加的,但是用absolute和relative也是可以的,但是一般情况下,添加的窗口是固定在屏幕的正中间,所以一般使用fixed

posted @ 2020-07-04 11:04  冉姑娘  阅读(1056)  评论(0编辑  收藏  举报