1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > html盒子模型图片居中 CSS盒模型和图片水平居中和垂直居中

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

时间:2019-08-31 18:34:11

相关推荐

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

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

.haha{

width: 500px;

height: 500px;

border: 1px solid #ccc;

margin: 0 auto;

}

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

.haha{

position: absolute;

width: 200px;

height: 200px;

border: 1px solid #ccc;

top: 50%;

margin-top: -100px;

}

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

.haha{

position: absolute;

width: 200px;

height: 200px;

border: 1px solid #ccc;

top: 50%;

left: 50%;

margin-top: -100px;

margin-left: -100px;

}

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

.haha{

width: 500px;

height: 500px;

text-align: center;

line-height: 500px;

}

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

.haha{

background:url(images/logo.png) no-repeat top center;

width: 300px;

height: 300px;

}

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

.haha{

background:url(images/logo.png) no-repeat left 50%;

width: 300px;

height: 300px;

}

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

.haha{

background:url(images/logo.png) no-repeat center center;

width: 300px;

height: 300px;

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。