美文网首页
子元素垂直水平居中的实现方式

子元素垂直水平居中的实现方式

作者: Amanda妍 | 来源:发表于2021-06-16 17:10 被阅读0次

    html部分:

    <div class="father">
        <div class="child"></div>
    </div>
    

    css部分控制:

    方式一:父元素相对定位 子元素绝对定位 left: 0;right: 0;top: 0;bottom: 0;margin: auto;
                .father{
                    width: 300px;
                    height: 300px;
                    background-color: salmon;
                    margin: 0 auto;
                    position: relative;
                }
                .child{
                    width: 100px;
                    height: 100px;
                    background-color: seagreen;
                    position: absolute;
                    left: 0;
                    right: 0;
                    top: 0;
                    bottom: 0;
                    margin: auto;
                } 
    
    方式二:父元素display:table-cell;vertical-align:middle
                子元素:margin:auto
                .father{
                    width: 300px;
                    height: 300px;
                    background-color: salmon;
                    margin: 0 auto;
                    display: table-cell;
                    vertical-align: middle;
                }
                .child{
                    width: 100px;
                    height: 100px;
                    background-color: seagreen;
                    margin: auto;
                
                }
    
    方式三:父元素相对定位 子元素绝对定位 left: 50%;
                    top: 50%;
                    margin-top: -50px;
                    margin-left: -50px;
                .father{
                    width: 300px;
                    height: 300px;
                    background-color: salmon;
                    position: relative;
                }
                .child{
                    width: 100px;
                    height: 100px;
                    background-color: seagreen;
                    position: absolute;
                    left: 50%;
                    top: 50%;
                    margin-top: -50px;//为自身高的一半
                    margin-left: -50px;//为自身宽的一半
                }
    
    方式四 父元素相对定位 子元素绝对定位 left:50%;top:50%;transform:translate(-50%,-50%)
                 .father{
                    width: 300px;
                    height: 300px;
                    background-color: salmon;
                    position: relative;
                }
                .child{
                    width: 100px;
                    height: 100px;
                    background-color: seagreen;
                    position: absolute;
                    left: 50%;
                    top: 50%;
                    transform: translate(-50%,-50%);
                }  
    

    相关文章

      网友评论

          本文标题:子元素垂直水平居中的实现方式

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