CSS盒模型和图片水平居中和垂直居中

盒子水平居中,使用margin:0 auto

<style>
.haha{
    width: 500px;
    height: 500px;
    border: 1px solid #ccc;
    margin: 0 auto;
}
</style>
<body>
    <div class="haha">
         
        </div>
</body>

盒子垂直居中,使用相对定位,以body为基准absolute,然后top:50%,但是盒子有高度所以还得margin-top:-100px,让盒子上移自己宽度的一半。

<style>
.haha{
    position: absolute;
    width: 200px;
    height: 200px;
    border: 1px solid #ccc;
    top: 50%;
    margin-top: -100px;
}
</style>
<body>
    <div class="haha">
         
        </div>
</body>

综上,如果要让div垂直居中,水平居中,就使用相对定位,以body为基准absolute,top left 50%并且减掉自身的一半,代码如下

<style>
.haha{
    position: absolute;
    width: 200px;
    height: 200px;
    border: 1px solid #ccc;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -100px;
}
</style>
<body>
    <div class="haha">
         
        </div>
</body>

当使用插入图片的方式时,img是行内元素所以只需要使用text-align:center和行高等于高,就能使图片水平居中垂直居中。

<style>
.haha{
    width: 500px;
    height: 500px;
    text-align: center;
    line-height: 500px;
}
</style>
<body>
    <div class="haha">
         <img src="images/logo.png">
        </div>
</body>

当使用背景图片水平居中,使用top center,代码如下:

<style>
.haha{
    background:url(images/logo.png) no-repeat top center;
    width: 300px;
    height: 300px;
}
</style>
<body>
    <div class="haha">
         
        </div>
</body>

当使用背景图垂直居中,代码如下,50%是参考值

<style>
.haha{
    background:url(images/logo.png) no-repeat left 50%;
    width: 300px;
    height: 300px;
}
</style>
<body>
    <div class="haha">
         
        </div>
</body>

背景图水平+垂直居中,如果需要图片全部铺满,则加上background-size: contain;

    <style>
.haha{
    background:url(images/logo.png) no-repeat center center;
    width: 300px;
    height: 300px;
}
    </style>
<body>
    <div class="haha">
         
        </div>
</body>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.绝对定位居中技术 我们一直用margin:auto实现水平居中,而一直认为margin:auto不能实现垂直居...
    DecadeHeart阅读 1,633评论 0 3
  • 一、CSS入门 1、css选择器 选择器的作用是“用于确定(选定)要进行样式设定的标签(元素)”。 有若干种形式的...
    宠辱不惊丶岁月静好阅读 1,651评论 0 6
  • 居中一直是CSS中被抱怨的典型。为什么实现起来这么辛苦?所以有人被嘲笑。我觉得问题不是没有办法做到,只是视情况而定...
    雨季诺言阅读 406评论 1 1
  • 前面学习了使用HTML为网页添加内容,要对所添加的内容进行布局,就需要使用到CSS,JS等,这里就记录一下自己关于...
    wxyzcctn阅读 572评论 0 3
  • 一 外部式css样式 (也可称为外联式)就是把css代码写一个单独的外部文件中,这个css样式文件以“.css...
    KunMitnic阅读 991评论 0 1