css实现垂直居中

使用 flex和position实现垂直居中

 一、使用position定位实现垂直居中

/*先声明浏览器最外层的高度 100%;*/
body,html{height:100%;}
/*父元素的宽、高,给一个position定位   父元素:#div0*/#div1{
  position: relative;
  width: 30%;
  height: 30%;
  background-color: lightblue;
  margin: 0 auto;
}
/*将元素垂直居中*/
#div1{
   position:absolute;
   top:50%;
   left:50%;
   background-color:white;
   transform:translate(-50%,-50%);
}
<body>
        <div id="div1">
            <div id="div2">
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            </div>
        </div>
    </body>

效果:

 二、使用flex实现垂直居中

/* 先声明最外层的高度 100%; */
            body,
            html {
                height: 100%;
            }

            /* 定义父元素为弹性盒 */
            #div1 {
                width: 30%;
                height: 30%;
                background-color: lightblue;
                margin: 0 auto;
                display: flex;
                align-items: center;
                /* //弹性盒内的元素为垂直居中 */
                justify-content: center;
                /* //将弹性盒内的元素水平居中 */
            }

            .div2 {
                width: 100px;
                height: 40px;
                background-color: #AAAAAA;
                text-align: center;
                line-height: 40px;
                margin-left: 1px;
            }

            .div2:first-child {
                margin-left: 0;
            }
        <body>
        <div id="div1">
            <div class="div2">
                垂直吧
            </div>
            <div class="div2">
                垂直吧
            </div>
            <div class="div2">
                垂直吧
            </div>
        </div>
    </body>    

效果:

 

 个人感觉flex布局比较简单

如果想学习,可以去http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html     看阮一峰老师写的笔记 

 

posted @ 2019-11-11 18:23  Name张三  阅读(118)  评论(0)    收藏  举报