让一个元素水平垂直居中

display:inline;转换为行内元素

display:block;转换为块状元素

display:inline-block;转换为行内块状元素

1.水平居中

对于确定宽度的块级元素

方法一:width和margin实现。

<head>
    <style type="text/css">
div{width: 80px;margin: 0 auto;} </style> </head> <body> <div>hello</div> </body>

方法二:绝对定位和left实现。(父级必须设置属性position:relation)

<head>
    <style type="text/css">
        body{position:relation}
        div{width: 400px;left:200px;position:absolute}
    </style>
</head>
<body>
    <div>hello</div>
</body>

对于宽度未知的块级元素

方法一:table标签和margin实现

<head>
    <style type="text/css">
        div{display: table;margin: 0 auto;}
    </style>
</head>
<body>
    <div>hello</div>
</body>

方法二:绝对定位和transform实现

<head>
    <style type="text/css">
        //当使用:top: 50%;left: 50%;, 是以左上角为原点,故不处于中心位置,translate(-50%,-50%) 作用是,往上(x轴),左(y轴)移动自身长宽的 50%,以使其居于中心位置
        div{position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);}
    </style>
</head>
<body>
    <div>hello</div>
</body>

方法三:flex布局(justify-content: center;属性)

<head>
    <style type="text/css">
        div{display: flex;justify-content: center;}
    </style>
</head>
<body>
    <div>hello</div>
</body>

对于行内块状元素(父级设置text-align: center属性)

<head>
    <style type="text/css">
        body{text-align: center}
        div{display:inline-block;}
    </style>
</head>
<body>
    <div>hello</div>
</body>

对于行内元素

方法一:为父级添加text-align: center;属性

<head>
     <style type="text/css">
         div{text-align: center;}
     </style>
 </head>
 <body>
     <div>
<span>hello</span>

</div> </body>

方法二:转化为块级元素

2.垂直居中

对于行内元素

<head>
     <style type="text/css">
         span{line-height: 300px;}
     </style>
 </head>
 <body>
     <span>hello</span>
</body>

对于已知高度的块级元素

弹性布局flex,添加属性height:400px;align-items: center;display: flex;实现垂直居中

对于未知高度的块级元素

table布局,父级添加属性display: table;,然后子级设置vertical-align实现。(需要注意的是:vertical-align: middle使用的前提条件是内联元素以及display值为table-cell的元素)

  

posted @ 2020-03-31 14:37  诉诉飞飞  阅读(178)  评论(1编辑  收藏  举报