• CSS居中问题


    Hello!我是super喵二!刚刚在写一个音乐播放器,其中用到ul没有设置宽高,由li撑起,然后需要居中显示在ul的父级div中。刚刚突然忘记了,然后查了下,最后出现居中效果,那就顺便总结下居中问题吧~~~

    一、水平居中

    1、行内元素(文字、图片、链接等):

      text-align: center;//对inline,inline-block,inline-table有效

    2、块元素(div/p等):

       margin: 0px auto;//无论宽度是否已知

    (不过加一句,就是开头的问题,我只需要设置ul的display:inline-block,就实现居中了,这个问题还在思考,不过建议最好将没有设置宽的块级元素设为inline-block,再将其父元素添加text-align:center;)

    3、多个块级元素

      如果有多个块元素需要水平居中时,有两种办法可以实现。一种是借助inline-block,另一种是借助flex。,设置块元素display:inline-block,其父元素水平居中:

     .div1 {    
        text-align: center;    
    }    
     .div1 div2 {    
        display: inline-block;    
    }
    

    用flex的话需要给块的父元素添加如下样式:

     .div1 {    
        display: flex;    
        justify-content: center;    
    }

    二、垂直居中

    1、行内元素:

      单行的行内元素:一种方法可以设置padding-top与padding-bottom的值相等来实现居中;另一种方法是知道高度,设置line-height=height。

      多行的行内元素可以考虑四种方法:

          one:设置padding-top与padding-bottom的值相等

          two:万能的flex布局{display: flex;justify-content: center; flex-direction: column; height: 400px;}

          three:vertical-align,这种用法才开始接触css时,我经常用但是没有效果,后来才发现要这样用呀(基本用在display为table里)

                       .div1 {display: table;}

                       .div1>div2 { display: table-cell;vertical-align: middle;}

          four:最后一种方法是在网上看到的:直接截个图吧:

                                                                                   

    2、块级元素:

       块级元素主要是通过定位设置margin,padding等:

          已知div2的高度时,假设相对其父元素是position:absolute

           { position: absoulte;top: 50%; height: 100px;margin-top: -70px; //这里70px是height*1/2 + padding padding: 20px;}

         块元素高度不知道时

            {transform: translateY(-50%);    
             top: 50%;    
             position: absoulte;} 

          万能的flex布局,和水平居中类似,只需要再加一句话:flex-direction: column;就ok了(flex布局还是蛮不错的,大家可以经常使用哇,菜鸟教程上都说了得到所有浏           览器的支持了哟)

    三、水平垂直居中:

       就是将以上一些组合使用就是了。

          比如flex布局,只需要加一句:align-items: center;     

     {  position: absoulte;
        top: 50%;    
        left: 50%;    
        margin: -120px 0px 0px -220px;    //height一半,width一半,另外加上padding值      
        height: 200px;    
         400px;    
        padding: 20px; 
    }

    {
      top: 50%;    
      left: 50%;    
      transform: translate(-50%, -50%);  
    }
    当然本文有自己的总结,也有从大神的博客中转载一些,具体情况具体讨论,大家多试试,就知道了~~~~~~~~~~如有错误/补充,欢迎提出!!!
  • 相关阅读:
    readystatechange事件
    DOMContentLoaded事件
    beforeunload事件
    jieba
    模型评估
    机器学习术语
    决策树
    kafka
    即时通讯好文
    HTTP头的Expires与Cache-control
  • 原文地址:https://www.cnblogs.com/cmmsuju/p/6940620.html
Copyright © 2020-2023  润新知