div网页居中

div样式网页居中

在开发中,有时候遇到需要将一个DIV放到网页的正中间,而自己的前端CSS基础,又不是很好,所以自己想着用博客的方式记录下来,以便忘记之后,可以来查询,废话不多说,直接上代码!

<body>
    <div class="main">
        <form th:action="@{/user/login}" method="post" class="form-class">
            <div>
                <h3>用户登入</h3>
            </div>
            <div class="item">
                <span>账号:</span> <input type="text" placeholder="请输入账号" name="name">
            </div>
            <div class="item">
                <span>密码:</span> <input type="password" placeholder="请输入密码" name="password">
            </div>
            <div class="item">
                <button type="submit">登入</button>
                <button type="reset">重置</button>
            </div>
        </form>
        <div class="msg" th:if="${msg !=null}">
            <h4 th:text="${msg}"></h4>
        </div>
    </div>
</body>
 <style>
        .main{
            text-align: center;
            background-color: cadetblue;
            color: #ffffff;
            width: 400px;
            height: 600px;
            margin: auto;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
        }
     .form-class{
         margin-top: 160px;
     }
        .item{
            margin-top: 40px;
        }
        .msg{
            color: red;
            margin-top: 40px;
        }
    </style>

效果如图所示:
在这里插入图片描述

第一种方式

div使用绝对布局,设置margin:auto;并设置top、left、right、bottom的值相等即可,不一定要都是0。

.main{
    text-align: center; /*让div内部文字居中*/
    background-color: #fff;
    border-radius: 20px;
    width: 300px;
    height: 350px;
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

第二种方式:

仍然是绝对布局,让left和top都是50%,这在水平方向上让div的最左与屏幕的最左相距50%,垂直方向上一样,所以再用transform向左(上)平移它自己宽度(高度)的50%,也就达到居中效果了,效果图和上方相同。

.main{
    text-align: center;
    background-color: #fff;
    border-radius: 20px;
    width: 300px;
    height: 350px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值