美文网首页
CSS盒模型和图片水平居中和垂直居中

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

作者: 雨中晨星 | 来源:发表于2020-03-07 00:00 被阅读0次

盒子水平居中,使用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>

相关文章

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

    盒子水平居中,使用margin:0 auto 盒子垂直居中,使用相对定位,以body为基准absolute,然后t...

  • css 图片居中

    css图片居中(水平居中和垂直居中) css图片水平居中 块状元素直接用text-align:center, di...

  • CSS图片居中(水平居中和垂直居中)

    css图片水平居中 css图片垂直居中 css图片水平垂直居中

  • 居中布局

    水平居中 垂直居中 垂直水平居中 已知元素的宽高的居中布局 定位居中布局 盒模型居中布局 图片的垂直水平居中(利用...

  • css 居中

    居中有水平居中和垂直居中。 水平居中+垂直居中 flex法 position法 就是计算呗~ 参考 CSS各种居中...

  • CSS解决盒模型居中的问题

    CSS实现盒子模型水平居中、垂直居中、水平垂直居中的多种方法 CSS实现盒子模型水平居中的方法 全局样式 第一种:...

  • CSS - 垂直水平居中方法

    前言 总括:整理 css 垂直水平居中方法,区分内联元素与块级元素 CSS垂直居中和水平居中 用css让一个容器水...

  • CSS居中完全指南——构建CSS居中决策树

    CSS居中完全指南——构建CSS居中决策树 本文总结CSS居中,包括水平居中和垂直居中.本文相当于CSS决策树,下...

  • CSS居中小结

    CSS居中总结 最近在学习CSS居中,居中里面又包含水平居中和垂直居中,分不太清内联元素(inline or in...

  • css水平居中和水平垂直居中

    水平居中和水平垂直居中demo

网友评论

      本文标题:CSS盒模型和图片水平居中和垂直居中

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