图片在div垂直水平居中的方法(持续更新)

1、vertical-align属性只会在inline-block水平的元素上期作用,例如图片,按钮,单复选框,单行/多行文本框等HTML控件,只有这些元素默认情况下会对vertical-align属性起作用.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
div{
width: 300px;
height: 300px;
background-color: red;
text-align: center;
line-height: 300px;
}
img{
width:100px;
height:100px;
vertical-align: middle;
}
</style>
</head>
<body>
<div>
<img src="http://pic9.nipic.com/20100916/2531170_131413079748_2.jpg">
</div>
</body>
</html>

效果如图:

2、利用绝对定位(不过感觉为什么视觉上并没有居中…)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    <style type="text/css">
body{
margin: 0;
padding: 0;
position: absolute;
width: 100%;
height: 100%;
text-align: center;
}
img{
position: absolute;
width: 100px;
height: 100px;
top:50%;
transform: translateY(-50%);
}
</style>
</head>
<body>
<img src="http://img5.duitang.com/uploads/item/201312/05/20131205172435_Sesdy.jpeg">
</body>

这里看demo

3、利用css3属性transform

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<style media="screen" type="text/css">
#appLoading { width: 100%; height: 100%; }
#appLoading img {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
transform: translateY(-50%) translateX(-50%);
}
</style>
<div id="appLoading">
<img src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3828227436,2721096501&fm=27&gp=0.jpg" alt="loading" />
</div>

这里看demo


图片在div垂直水平居中的方法(持续更新)
https://xypecho.github.io/2018/01/16/图片在div垂直水平居中的方法-持续更新/
作者
很青的青蛙
发布于
2018年1月16日
许可协议