• 聊聊css居中的那些事


    长久以来 css的水平居中,垂直居中,水平垂直居中 我都比较混乱 每次都是试对了就行,今天好好总结一下

    1.行内元素水平居中

    <style>
        div{
            background-color:cadetblue;
            width: 500px;
            text-align: center;
        }
    </style>
    <body>
        <div>
            我是文本,我只相对于父元素水平居中
        </div>
    </body>

     2.块状元素的水平居中,分为:定宽块状元素和不定宽块状元素

    定宽块状元素水平居中显示

    •   最常使用的margin 方式 margin: auto auto为垂直水平居中
    <style>
        div{
            background-color:cadetblue;
            width: 500px;
            /* margin-left和margin-right设置auto,margin-top和margin-bottom可以不为0 */
            margin: 0 auto;
        }
    </style>
    <body>
        <div>
            我是定宽块状元素,我想水平居中显示
        </div>
    </body>
        • 使用flex布局实现水平垂直居中
        • 一定要把这里的flex-center挂在父级元素,才能使得其中 唯一的子元素居中
    <style> 
        .wrapper {
            width: 300px;
            height: 300px;
            border: 1px solid #ccc;
        }
        .flex-center {
            display: flex;
            /* 水平居中 */
            justify-content: center;
            /* 垂直居中 */
            align-items: center;
        }
    </style>
    <body>
        <div class="wrapper flex-center">
            <div>
                我要居中
            </div>
        </div>  
    </body>

    不定宽块状元素水平居中

      1.给要居中的块状元素外一个table标签,然后让table标签居中,个人不推荐这种方式

    <style>
        table{
            background-color: yellow;
            margin: 0 auto;
        }
    </style>
    <body>
       
    <table>
        <tbody>
          <tr><td><div>
         设置我所在的div容器水平居中 
       </div>
       </td></tr>
        </tbody>
       </table

     2.将不定宽块状元素display为内联元素

    <style>
        ul{
            background-color:red;
            display: inline;
            text-align: center;
           
        }
    </style>
    <body>
        
          <ul>
              <li>1</li>
              <li>2</li>
              <li>3</li>
          </ul>
    </body>

    效果(没有弄清楚为什么左上角还有显示红色)

  • 相关阅读:
    基于物品属性的过滤
    第一个极小的机器学习的应用
    基于物品过滤的Slope One 算法
    【转】Python爬虫(1)_基本原理
    程序猿面试题集锦
    Django:popup弹出框简单应用实例
    【转】Python max内置函数详细介绍
    MySQL数据库(9)_MySQL数据库常用操作命令
    【转】Python的hasattr() getattr() setattr() 函数使用方法详解
    Git常用命令
  • 原文地址:https://www.cnblogs.com/yaolei0422/p/14470199.html
Copyright © 2020-2023  润新知