上下左右居中显示,多种方式

已知宽高的div左右居中

<!DOCTYPE html>
<html>
<head>
    <title>div水平居中</title>
    <style type="text/css">
        .myDiv{
            width: 300px;
            height: 300px;
            margin: auto;
            background: grey;
        }
    </style>
</head>
<body>
    <div class="myDiv">
        this is my div!
    </div>
</body>
</html>

未知宽高的div上下左右居中

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>title</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        body,html{
            height: 100%;
        }
        body{
            text-align: center;
        }
        span{
            display: inline-block;
            height: 100%;
            vertical-align: middle;
        }
        div{
            width: 400px;
            border: solid 1px red;
            vertical-align: middle;
            display: inline-block;
            *display: inline;
            *zoom:1;
            text-align: left;
        }
    </style>
</head>
<body>
    <span></span><div class="box">测试文字<br>asdfasdf<br>asdafasdfsdafadsf</div>
</body>
</html>

利用flex布局实现上下左右居中

<!DOCTYPE html>
<html>
<head>
    <title>div包含子div垂直居中对齐</title>
    <style type="text/css">
        body{
            /*width: 500px;*/
            height: 300px;
            border: 4px solid purple;
            display: flex;            /*设置flex布局*/
            justify-content: center;/*水平居中*/
            align-items: center;/*竖直居中*/
        }
        .inner{
            width: 160px;
            height: 160px;
            font-size: 26px;
            border: 1px solid green;
        }
    </style>
</head>
<body>
    <div class="demo">
        <div class="inner">
            <p>这是一个测试这是一个测试</p>
        </div>
    </div>
</body>
</html>

已知宽高,实现上下左右居中

<!DOCTYPE html>
<html>
<head>
    <title>已知宽高div上下左右居中</title>
    <style type="text/css">
        .main{
            width: 400px;
            height: 300px;
            position: absolute;
            left: 50%;
            top: 50%;
            margin: -150px 0 0 -200px;
            background: green;
        }
    </style>
</head>
<body>
    <div class="main">
        this is my div!!!
    </div>
</body>
</html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值