美文网首页
margin:auto与水平居中

margin:auto与水平居中

作者: WangYatao | 来源:发表于2016-11-07 13:20 被阅读44次

    auto:自动填充
    当margin-right设置为100px,margin-left设置为auto
    那么margin-left的值为屏幕总的宽度减去100px

    Paste_Image.png

    左右均为auto,水平居中显示
    当margin-left与margin-right设置为auto
    则平分剩余空间,也就是橙色部分会位于中间部位

    Paste_Image.png
      background: lightcoral;
      width: 500px;
      margin-right: 100px;
      margin-left: auto;
    

    对于图片的margin:0 auto;此时图片属于inline水平,并没有撑满整个容器,不存在剩余空间
    因为它没有剩余的填充,所以设置auto,并没有任何变化

    Paste_Image.png

    为了使图片居中显示可以给图片img添加display:block;属性,使图片占据一行,从而有剩余的填充空间

    Paste_Image.png
            <style type="text/css">
                  img{
                        width: 200px;
                        margin: 0 auto;
                        }
            </style>
    

    inline-block属性的水平居中,它是一个行内的块级元素,使元素成块状并且在一行排列,对于这样的元素水平居中,我个人觉得最方便的就是设置父类元素text-align:center;使元素水平居中

    Paste_Image.png

    相关文章

      网友评论

          本文标题:margin:auto与水平居中

          本文链接:https://www.haomeiwen.com/subject/tokouttx.html