css怎么让图片垂直左右居中?(外层div是浮动且按照百分比排列)
一、原始的居中方法是把div换成table
<
div
style
=
"width: 500px; height: 200px; border: solid 1px red; text-align: center"
>
<
img
src
=
"http://www.baidu.com/img/baidu_jgylogo3.gif"
/>
</
div
>
<
div
style
=
"width: 500px; height: 200px; border: solid 1px red;"
>
<
center
>
<
img
src
=
"http://www.baidu.com/img/baidu_jgylogo3.gif"
/>
</
center
>
</
div
>
<
table
style
=
"width: 500px; height: 200px; border: solid 1px red; text-align:center"
>
<
tr
>
<
td
>
<
img
src
=
"http://www.baidu.com/img/baidu_jgylogo3.gif"
/>
</
td
>
</
tr
>
</
table
>
二、但是如果外层div是浮动且按照百分比排列的话,你要怎么做?
此时,请看图下的关键代码,可实现不同分辨率下的图片垂直左右居中。
<!doctype html>
<
html
>
<
head
>
<
meta
charset
=
"utf-8"
>
<
title
>图片垂直水平居中</
title
>
<
style
>
div{height:500px;width:400px;text-align:center;border:1px solid #000;margin:20px auto;}
img{vertical-align:middle;} /* 关键代码 */
span{height:100%;display:inline-block;vertical-align:middle;} /* 关键代码 */
</
style
>
</
head
>
<
body
>
<
div
>
<
img
src
=
"http://img.o571.com/fc/ad/20130827161606949.jpg"
width
=
"323"
height
=
"215"
/>
<
span
></
span
>
</
div
>
</
body
>
</
html
>