元素居中的几种方式

简介: 元素居中的几种方式

1:设置元素绝对定位,通过margin属性,移动自身宽高的一半

2:设置元素绝对定位,设置margin:auto

3:设置弹性布局,通过align-items: center;justify-content: center;实现

4:设置元素绝对定位,通过transform属性,移动自身宽高的一半

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html,body{width:100%;height:100%}
        /* 元素水平及垂直实现方式1 */
        #d1{
            position: relative;
            width:100%;
            height:100%;
            background-color:#f00;
        }
        .children{
            position:absolute;
            width:100px;
            height:100px;
            left:50%;
            top:50%;
            margin-left:-50px;
            margin-top:-50px;
            background-color:#fff;
        }
        /* 元素水平及垂直实现方式2 */
        #d1{
            position: relative;
            width:100%;
            height:100%;
            background-color:#f00;
        }
        .children{
            position:absolute;
            width:100px;
            height:100px;
            left:0;
            top:0;
            right:0;
            bottom:0;
            margin:auto;
            background-color:#fff;
        }
        /* 元素水平及垂直实现方式3 */
        #d1{
            width:100%;
            height:100%;
            background-color:#f00;
            display:flex;
            align-items: center;    /*垂直居中*/
            justify-content: center;    /*水平居中*/
        }
        .children{
            display: inline-block;
            width:100px;
            height:100px;
            background-color:#fff;
        }
        /* 元素水平及垂直实现方式4 */
        #d1{
            position: relative;
            width:100%;
            height:100%;
            background-color:#f00;
        }
        .children{
            position:absolute;
            width:100px;
            height:100px;
            background-color:#fff;
            left:50%;
            top:50%;
            transform: translate(-50% -50%);
        }
    </style>
</head>
<body>
    <div id="d1">
        <div class="children"></div>
    </div>
</body>
</html>


相关文章
|
1月前
单元格内容的对齐方式
单元格内容的对齐方式。
14 0
|
20天前
【奇技淫巧】实现flex布局中,单独某个元素挪到右侧、底部,与其他元素排列不同,就像是个另类。(主要是用到margin-left和align-self)
【奇技淫巧】实现flex布局中,单独某个元素挪到右侧、底部,与其他元素排列不同,就像是个另类。(主要是用到margin-left和align-self)
|
4月前
|
前端开发 容器
css中元素水平居中的方式
css中元素水平居中的方式
46 0
|
7月前
|
移动开发
操作元素样式
操作元素样式
|
8月前
|
容器
【元素水平垂直居中的方法有哪些?元素不定宽高呢?】
【元素水平垂直居中的方法有哪些?元素不定宽高呢?】
【元素水平垂直居中的方法有哪些?元素不定宽高呢?】
|
8月前
元素水平垂直居中的六种方法
元素水平垂直居中的六种方法
63 1
span标签溢出元素设置省略号
span标签溢出元素设置省略号
125 0
|
前端开发
如何优雅地为列表非首项元素添加样式,关键靠他们。
在开发中我们常常会会遇到列表相关的场景,比如说:卡片列表,导航栏等等。
82 4
如何优雅地为列表非首项元素添加样式,关键靠他们。
hover时行级元素变成了块级元素,导致位置错乱
hover时行级元素变成了块级元素,导致位置错乱