flex布局和垂直居中方法总结

flex布局可以参考以下的文章内容,较为详细

https://www.ruanyifeng.com/blog/2015/07/flex-grammar.html

http://www.ruanyifeng.com/blog/2015/07/flex-examples.html

网页布局的传统解决方案,基于盒状模型,依赖 display 属性 + position属性 + float属性。它对于那些特殊布局非常不方便,比如,垂直居中就不容易实现。

2009年,W3C 提出了一种新的方案----Flex 布局,可以简便、完整、响应式地实现各种页面布局。目前,它已经得到了所有浏览器的支持。

垂直居中的解决方案(如下效果所示):
在这里插入图片描述
1.
父元素设置相对定位
子元素设置绝对定位 margin auto

<body>
     <div id = "box">
         <div id = "child">

         </div>
     </div>

</body>
<style>
    #box{
        width: 300px;
        height: 300px;
        background-color: crimson;
        position: relative;
    }
    #child{
        width: 150px;
        height: 100px;
        background-color:blueviolet;
        position: absolute;
        top:0;
        bottom: 0;
        left:0;
        right: 0;
        margin:auto;
    }
</style>

父元素设置flex
flex-direction:column;
justify-content: center;
子元素设置
align-self: center;

<style>
    #box{
        width: 300px;
        height: 300px;
        background-color: crimson;
        display: flex;
        flex-direction:column;
        justify-content: center;
    }
    #child{
        width: 150px;
        height: 100px;
        background-color:blueviolet;
       align-self: center;
    }
</style>

父元素设置相对定位
子元素设置绝对定位
top:50%;
left:50%;
transform:translate(-50%,-50%);

<style>
    #box{
        width: 300px;
        height: 300px;
        background-color: crimson;
        position: relative;
    }
    #child{
        width: 150px;
        height: 100px;
        background-color:blueviolet;
        position:absolute;
        top:50%;
        left:50%;
        transform:translate(-50%,-50%);
       //向上,向左调整50%
    }
</style>

父元素
display: table;
子元素:
display: table-cell;
vertical-align:center;

<style>
    #box{
        width: 300px;
        background-color: crimson;
        padding: 100px;
        display: table;
    }
    #child{
        width: 100px;
        height: 100px;
        background-color:blueviolet;
       display: table-cell;
        vertical-align:center;
    }
</style>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值