zoukankan      html  css  js  c++  java
  • 聊聊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>

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

  • 相关阅读:
    poj2778 DNA Sequence(AC自动机+矩阵快速幂)
    poj2001 Shortest Prefixes (trie树)
    hdu5536 Chip Factory
    解决 苹果手机点击输入框页面自动放大111
    css 记录
    对复选框自定义样式 优化方法
    css引入外部字体
    jquery获取当前页面的URL信息
    左侧导行伸缩控制
    表单提交同类数据的做成数组
  • 原文地址:https://www.cnblogs.com/yaolei0422/p/14470199.html
Copyright © 2011-2022 走看看