Maison > interface Web > tutoriel CSS > le corps du texte

CSS如何实现垂直水平居中

不言
Libérer: 2018-06-12 15:34:41
original
2423 人浏览过

这篇文章主要介绍了关于CSS如何实现垂直水平居中,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

前言

面试中常常被问到,如何使用css来实现一个元素的垂直水平方向上居中,特别是笔试题的时候,这道题目的出现频率还是比较高的,当然,在我们的生活中,也常常会有垂直水平居中的需求。

CSS实现垂直水平居中的三种方案

1.容器内元素display:inline/inline-block

这种情况就比较容易了,直接设置容器的text-align就可以实现内容元素的水平居中,设置垂直居中的话要设置容器的高度,然后设置容易的line-height===height就可以,如下:

     

this is text

Copier après la connexion
    .container{    
        text-align: center;        
        height: 50px;        
        background: green;        
        line-height: 50px;    
        }
Copier après la connexion

2.容器内元素display:block,且元素宽高已知

这种情况下我们使用position这个属性结合设置偏移来实现。首先设置容器的position:relative,设置元素position为absolute,然后设置元素(.inner-box)的偏移top,left,margin-top,margin-left,其中,top,left设置为50%,而margin-top/margin-left的偏移量均为本身元素高/宽的一半,为负值。

代码如下:

    

Copier après la connexion
    .container {        
        height: 200px;        
        width: 200px;        
        background: pink;        
        position: relative;    
        }

    .inner-box {       
     position: absolute;        
     top: 50%;        
     left: 50%;        
     margin-top: -50px;        
     margin-left: -50px;        
     height: 100px;        
     width: 100px;        
     background: green;    
     }
Copier après la connexion

3.容器内元素display:block,且元素宽高未知

这种方法与方法二类似,但是不同的是不能通过设置margin-top/left偏移来达到效果了,因为容器内元素的宽高是未知的。这次我们通过设置left/top/bottom/right:0,然后设置margin:auto。
代码如下:

    

Copier après la connexion
    .container {        
        height: 200px;            
        width: 200px;            
        background: pink;            
        position: relative;        
        }

    .inner-box {     
       position: absolute;        
       height: 100px;        
       width: 100px;        
       top: 0;        
       right: 0;        
       left: 0;        
       bottom: 0;        
       margin: auto;        
       background: green;    
       }
Copier après la connexion

后话

实现垂直水平居中的方式有多种,通过设置translate,或者使用flex布局也是可以的,但是以上写的几种方法是兼容性比较好的。如果有不足,欢迎这位大佬指出。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

利用CSS实现各种居中的方法

以上是CSS如何实现垂直水平居中的详细内容。更多信息请关注PHP中文网其他相关文章!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!