← 返回首页

css水平居中和垂直居中

2020-11-09

如何让一个子元素在父容器里水平垂直居中

文字、图片等行内元素水平垂直居中

行内元素水平居中

父容器设置

text-align: center;

行内元素垂直居中

父容器设置

.father { height: 20px; line-height: 20px; }

块级元素水平垂直居中

块级元素水平居中

margin:0 auto; 

或者

margin:auto;

块级元素垂直居中

方式一:绝对定位 + margin 让子元素的左上角居中,然后向上移动宽度的一半(50px),就达到了垂直居中的效果,但是需要指定子元素的宽高。

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { margin: 0; padding: 0; } .father{ position: relative; min-height: 500px; background: pink; } .son { position: absolute; width: 200px; height: 100px; background: red; top: 50%; left: 50%; margin-top: -50px; margin-left: -100px; } </style> </head> <body> <div class="father"> <div class="son">子元素的内容</div> </div> <script></script> </body> </html> 方式二:绝对定位 + translate 不需要指定狂傲,translate()函数中使用百分比值时,是以这个元素自身的宽度和高度为基准进行换算和移动的(动态计算宽高)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { margin: 0; padding: 0; } .father{ position: relative; min-height: 500px; background: pink; } .son { position: absolute; background: red; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style> </head> <body> <div class="father"> <div class="son">子元素的内容</div> </div> <script></script> </body> </html> 方式三:flex 布局 + margin: auto 同时水平、垂直居中

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;Document&lt;/title&gt;
    &lt;style&gt;
        * {
            margin: 0;
            padding: 0;
        }
        .father{
            display: flex;
            min-height: 100vh;
            background: pink;
        }
        .son {
            margin: auto;
            background: red;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div class=&quot;father&quot;&gt;
        &lt;div class=&quot;son&quot;&gt;子元素的内容,想水平垂直居中&lt;/div&gt;
        &lt;div class=&quot;son2&quot;&gt;这个元素不想水平垂直居中&lt;/div&gt;
    &lt;/div&gt;
    &lt;script&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
pigchen.github.io