300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 如何使img或者div在div中水平垂直居中显示

如何使img或者div在div中水平垂直居中显示

时间:2024-04-08 08:07:32

相关推荐

如何使img或者div在div中水平垂直居中显示

闲来无事,被人问到如何使img在一个div中垂直居中显示,自己就总结了如下几种方法,供大家参考:

方法一:在box中添加span空元素

<div id="box"><div class="img"></div><span></span></div>

#box{width: 200px;height: 200px;background:black;margin:0 auto;text-align: center;}.img{width: 100px;height: 100px;background:white;display: inline-block;vertical-align: middle;}#box span{display: inline-block;width:0;height:100%;vertical-align: middle;}

方法二:使用定位法,使用定位法时,img包含两种情况:

(1)固定宽高

<div id="box"><div class="img"></div></div>

#box{width: 200px;height: 200px;background:black;margin:0 auto;text-align: center;position: relative;}.img{width: 100px;height: 100px;position: absolute;background: white;left:50%;top:50%;margin-top:-50px;margin-left:-50px;}

(2)无固定宽高

<div id="box"><div class="img"></div></div>

#box{width: 200px;height: 200px;background:black;margin:0 auto;text-align: center;position: relative;}.img{width: 100px;height: 100px;position: absolute;background: white;left:50%;top:50%;-webkit-transform: translate(-50%,-50%);-moz-transform:translate(-50%,-50%);-ms-transform: translate(-50%,-50%);-o-transform: translate(-50%,-50%);transform: translate(-50%,-50%);}

方法三:设置父div为table-cell属性

<div id="box"><div class="img"></div></div>

#box{width: 200px;height: 200px;background:black;display: table-cell;text-align: center;vertical-align: middle;}.img{width: 100px;height:100px;background: white;display: inline-block;}

方法四:使用flex布局

<div id="box"><div class="img"></div></div>

#box{width: 200px;height: 200px;background:black;text-align: center;display: flex;justify-content: center;align-items: center;margin:0 auto;}.img{width: 100px;height:100px;background: white;}

前两种是在开发中用的比较多的,最后一种在移动端布局使经常使用,只限子元素只有一个元素的情况下,以上为本人的见解,如有错误还请大家指正!

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