美文网首页
关于垂直居中css

关于垂直居中css

作者: 米卡卡米 | 来源:发表于2019-10-16 16:41 被阅读0次

1.使用text-align:center/line-height:高度一半进行居中


image.png
 .center1 {
            width: 100px;
            height: 100px;
            background-color: cadetblue;
            text-align: center;
            line-height: 100px;
            margin: auto;
        }
html
   <div class="center1">水平文字居中</div>
  • 这种居中,如果不设置宽高,则会铺满整个父元素
  1. position方法之:transform: translate(-50%, -50%); top:50% left:50%


    image.png

        .outer2 {
            width: 200px;
            height: 200px;
            border: 1px solid red;
            position: relative;
            /*写在父元素上,绝对定位*/
        }

        .center2 {
            width: 100px;
            height: 100px;
            background-color: antiquewhite;
            position: absolute;
            /*写在子元素上,相对定位,相对父元素定位*/
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
html
  <div class="outer2">
        <div class="center2">水平垂直居中(未知宽高)</div>
    </div>
  1. position方法之: margin: -50px 0 0 -50px;(宽高一半)
   .outer3 {
            width: 200px;
            height: 200px;
            border: 1px solid red;
            position: relative;
            /*写在父元素上,绝对定位*/
        }

        .center3 {
            width: 100px;
            height: 100px;
            background-color: antiquewhite;
            position: absolute;
            /*写在子元素上,相对定位,相对父元素定位*/
            top: 50%;
            left: 50%;
            margin: -50px 0 0 -50px;
        }
  1. position方法之: top: 0;left: 0;right: 0;bottom: 0;

        .outer4 {
            width: 200px;
            height: 200px;
            border: 1px solid red;
            position: relative;
            /*写在父元素上,绝对定位*/
        }

        .center4 {
            width: 100px;
            height: 100px;
            background-color: antiquewhite;
            position: absolute;
            /*写在子元素上,相对定位,相对父元素定位*/
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
        }

5.水平垂直居中内联元素

.outer5 {
            width: 200px;
            height: 200px;
            border: 1px solid red;
            display: flex;
            justify-content: center;
            /*水平居中*/
            align-items: center;
            /*垂直居中*/
        }

        .center5 {
            width: 100px;
            height: 100px;
            background-color: blueviolet;
        }

下面几个效果图都如上图

相关文章

网友评论

      本文标题:关于垂直居中css

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