2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > css图片如何垂直水平居中设置

css图片如何垂直水平居中设置

时间:2023-08-09 03:19:34

相关推荐

css图片如何垂直水平居中设置

css设置图片垂直居中的方法:

一、使用flex实现垂直居中

利用css flex实现垂直居中,有些浏览器可能不兼容flex。

首先要创建一个包裹着图片的div元素,然后定义基础属性。

以下图片img宽度为(设置为)100px,高度为100px。

HTML代码部分:

<style>.flexbox{width: 300px;height: 250px;background:#ccc;display: flex;align-items: center;text-align:center; }.flexbox img{width: 100px;height: 100px;margin:0 auto;}</style><div class="flexbox"><img src="img.png" alt=""></div>

二、利用Display: table;实现img图片垂直居中

1、先创建一个div元素以及另外一个包含图片的div元素,设置样式

2、给img父元素设置display:table

3、包裹图片的父类div元素设置display:table-cell

<style>.tablebox{width: 300px;height: 300px;background: #fff;display: table;background: #ccc;}#imgbox{display: table-cell;vertical-align: middle; text-align: center;}#imgbox img{width: 100px;}</style><div class="tablebox"><div id="imgbox"><img src="img.png" alt=""></div></div>

三、用绝对定位实现垂直居中

<style>.posdiv{width: 300px;height: 300px;background: #eee;position: relative; text-align:center; }.posdiv img{width: 100px;position: absolute;top: 50%;margin-top: -50px;margin-left: -50px;}</style><div class="posdiv"><img src="img.png" alt=""></div>

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