菜鸟笔记
提升您的技术认知

CSS 元素居中

阅读 : 889

flex布局

使用flex,只需要给父元素设置即可。若想只水平/垂直居中,则注释对应代码即可。

           /* 父元素 */
            .container{
  
                width: 500px;
                height: 500px;
                background-color: blue;

                display:flex;
                align-items: center ;   /*控制垂直居中*/
                justify-content: center;/*控制水平居中*/
            }
            /* 子元素 */
            .item{
  
                width: 200px;
                height: 200px;
                background-color: red;
            }

  • grid布局

使用grid,与flex类似。只需要给父元素设置即可。若想只水平/垂直居中,则注释对应代码即可。

            /* 父元素 */
            .container{
  
                width: 500px;
                height: 500px;
                background-color: blue;

                display:grid;
                align-items: center ;   /*控制垂直居中*/
                justify-content: center;/*控制水平居中*/
            }
            /* 子元素 */
            .item{
  
                width: 200px;
                height: 200px;
                background-color: red;
            }
  • margin:auto

在使用 margin:auto使元素居中时,需要给父元素设置为position:relative;子元素设置position: absolute;具体实现垂直水平居中的代码如下。

 /* 父元素 */
            .container{
  
                width: 500px;
                height: 500px;
                background-color: blue;

                position: relative;
            }
            /* 子元素 */
            .item{
  
                width: 200px;
                height: 200px;
                background-color: red;
               
                position: absolute;
                
                /* 垂直居中 */
                /* 
                top: 0; 
                bottom: 0; 
                margin: auto 0; 
                */

                /* 水平居中 */
                /*                 
                left: 0; 
                right: 0; 
                margin: 0 auto; 
                */

                /* 水平+垂直居中 */               
                left: 0; 
                right: 0; 
                top: 0; 
                bottom: 0; 
                margin: auto; 
               
            }

  • translate

  • 在使用 translate使元素居中时,需要给父元素设置为position:relative;子元素设置position: absolute;具体实现垂直水平居中的代码如下。
            /* 父元素 */
            .container{
  
                width: 500px;
                height: 500px;
                background-color: blue;

                position: relative;
            }
            /* 子元素 */
            .item{
  
                width: 200px;
                height: 200px;
                background-color: red;
               
                position: absolute;
                
                /* 水平居中 */
                /* left:50%;
                transform: translate(-50%, 0); */
                
                /* 垂直居中 */
                /* top:50%;
                transform: translate(0, -50%); */

                /* 水平+垂直居中 */
                left:50%;
                top:50%;
                transform: translate(-50%, -50%);
            }