1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 让行内元素(如图片)在div中水平垂直居中 (干货)

让行内元素(如图片)在div中水平垂直居中 (干货)

时间:2020-07-28 10:54:30

相关推荐

让行内元素(如图片)在div中水平垂直居中 (干货)

(1)第一种:用vertical-align

<div class="method1"><span class="tiptop"></span><img class="test" src="img/Dota2.jpg" alt="dota2"></div><style>.method1{text-align:center;}/*vertical-align:middle 是依赖div内子元素最高的行高来实现对某元素居中的,而我们只需要建立一个新元素,给他加上inline-block属性 再把他高度设置为100%就行了,在下面的<img>设置vertical-align就生效了*/.tiptop{height:100%;display:inline-block;vertical-align:middle;}img{vertical-align:middle;}</style>

(2)第二种:flex布局(注意浏览器兼容性)

<div class="method2"><img src="img_p1_title.png"></div><style>.method2 {display: flex;justify-content: center; //弹性盒子对象在主轴上的对齐方式align-items: center;//定义flex子项在flex容器的当前行的侧轴(纵轴)方向上的对齐方式。background-color:#00a0e9;height:200px;}.method2 img {width:20px;height:30px;background-color:#0A58A0;}</style>

(3)position:absolute;绝对定位方式

<div class="method3"><span>第三种方法</span></div><style>.method3 {width:100%;height: 200px;font-size: 18px;position: relative;background-color:#00a2d4;}.method3 span {width:100px;height:100px;background-color:#00ACED;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);}</style>

(4)使用display:table-cell配合vertical-align:center(淘宝也是这样用的)

<div class="method4"><span>第四种方法</span></div><style>.method4 {width: 200px;height: 200px;vertical-align: middle;display: table-cell; /*只支持IE8+及现代浏览器,与position:absolute;或float:left;属性尽量不一起用*/text-align: center;background-color:#00ACED;}.method4 span{width:100px;height:100px;background-color:#0A58A0;}</style>

简单易懂吧,点个赞

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