css使元素水平垂直居中总结

在下面的演示代码中,用到的html结构为:

<div class="content">
    <div class="center"></div>
</div>

方法一:positoin+margin

        .content{
            height: 200px;
            width: 200px;
            background-color: #ccc;
            position: relative;
        }
        .center{
            width: 100px;
            height: 100px;
            background-color: pink;
            margin: auto;
            position:absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0; 
        }

方法二:display:tell-cell;

.content{
            height: 200px;
            width: 200px;
            background-color: #ccc;
            display: table-cell;
            vertical-align: middle;
            text-align: center;
        }
        .center{
            display: inline-block;
            width: 100px;
            height: 100px;
            background-color: pink;
            vertical-align: middle;
            
        }

方法三:display:flex;align-items:center;justify-content:center;

        .content{
            height: 200px;
            width: 200px;
            background-color: #ccc;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .center{
             background-color: pink;
             width: 100px;
             height: 100px;
        }

方法四:display:flex;margin:auto;(主要适用移动端)

          .content{
            height: 200px;
            width: 200px;
            background-color: #ccc;
            display: flex;
        }
        .center{
            background-color: pink;
               width: 100px;
            height: 100px;
            margin: auto;
        }

方法五:纯position

          .content{
            height: 200px;
            width: 200px;
            background-color: #ccc;
            position: relative;
        }
        .center{
            background-color: pink;
             width: 100px;
            height: 100px;
            position: absolute;
            left: 50px;
            top: 50px;
        }

content{
height: 200px;
width: 200px;
background-color: #ccc;
position: relative;
}
.center{
background-color: pink;
width: 100px;
height: 100px;
position: absolute;
left: 50%;
margin-left: -50px;//-1/2宽度
top: 50%;
margin-top: -50px;//-1/2高度
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 各种纯css图标 CSS3可以实现很多漂亮的图形,我收集了32种图形,在下面列出。直接用CSS3画出这些图形,要比...
    剑残阅读 9,720评论 0 8
  • 1.长方形 #Rectangle{ width: 200px; height: 50px; background-...
    一直以来都很好阅读 520评论 0 0
  • 今天是情人节,此时写此文,算是凑凑热闹吧,但愿没有拉仇恨。 关于爱情与面包不可兼得,大致分为两派。一派为要面包不要...
    山涧静流阅读 1,031评论 0 1
  • 7.20晚作业:抽人像卡代表在瘦身阶段,你正在压抑的自己是什么样的(四张起) 压抑的自己是多愁伤感,表面装和平,无...
    小旭_b25d阅读 231评论 0 1
  • 上周一个女(的)朋友和我诉苦,她说自己的感情出现了危机,她想离开那个男生,然后决绝地做一个不婚主义者。 我当时不知...
    帽修阅读 304评论 0 2