您的位置:首页 > Web前端 > CSS

兼容各种浏览器的图片垂直居中CSS解决方案

2017-07-25 18:01 585 查看
参考文献

兼容各种浏览器的图片垂直居中CSS解决方案

css-使不同大小的图片在固定大小的容器中居中

1 利用hack来使图片垂直居中

<style>
.box {
/*非IE的主流浏览器识别的垂直居中的方法*/
display: table-cell;
vertical-align:middle;

/*设置水平居中*/
text-align:center;

/* 针对IE的Hack */
*display: block;
*font-size: 175px;/*约为高度的0.873,200*0.873 约为175*/
*font-family:Arial;/*防止非utf-8引起的hack失效问题,如gbk编码*/

width:200px;
height:200px;
border: 1px solid red;
}
.box img {
/*设置图片垂直居中*/
vertical-align:middle;
}
</style>
<div class="box">
<img src="http://pics.taobao.com/bao/album/promotion/taoscars_180x95_071112_sr.jpg" />
</div>
效果



但是table-cell 很难实现width:100%

2 通过相对和绝对布局实现图片垂直居中

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<style>
.imgbox{
position: relative;
width: 240px;
height: 240px;
border: 1px red solid;
}
.imgbox img{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
max-width: 100%;
max-height: 100%;
outline: 1px solid #000;
}
</style>

<title>Insert title here</title>
</head>
<body>

<div class="imgbox">
<img src="static/img/chat.ico" alt="xxxxx"/>
</div>
</body>
</html>

说明:imgbox为放置图片的容器,高度和宽度可以设置为任意需要的大小,容器中的图片为绝对定位,使用top-bottom-left-right-margin使其居中。使用max-width和max-height使图片比容器大时也能正常显示。
效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: