首页 > 其他 > 详细

元素居中的两种方法,transform和margin

时间:2017-10-10 12:04:43      阅读:269      评论:0      收藏:0      [点我收藏+]

1.transform :translate(-50%,-50%)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        body,
        html {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0
        }
        
        .box {
            width: 100%;
            height: 100%;
            background: red
        }
        
        .div1 {
            width: 200px;
            height: 200px;
            background: black;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%)
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="div1"></div>
    </div>

</body>

</html>

2.top,bottom,left,right和margin:auto

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        body,
        html {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0
        }
        
        .box {
            width: 100%;
            height: 40%;
            background: red;
            position: relative
        }
        
        .div1 {
            width: 200px;
            height: 200px;
            background: black;
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="div1"></div>
    </div>

</body>

</html>

 

元素居中的两种方法,transform和margin

原文:http://www.cnblogs.com/moxiaowohuwei/p/7644888.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!