Skip to content

Instantly share code, notes, and snippets.

@Jimco
Last active August 29, 2015 14:01
Show Gist options
  • Save Jimco/39c140f5b0f1478def8d to your computer and use it in GitHub Desktop.
Save Jimco/39c140f5b0f1478def8d to your computer and use it in GitHub Desktop.
未知宽高文字/图片,水平垂直居中解决方案
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Vertically centring in css</title>
<style>
.imgbox{display:table-cell; width:200px; height:200px; text-align:center; vertical-align:middle; *display:block; *position:relative; margin:20px auto;border:1px solid #ccc;}
.imgbox div{margin:0; *position:absolute; *top:50%; *left:50%;}
.imgbox div img{vertical-align:middle; *position:relative; *top:-50%; *left:-50%;}
.txtbox {width:200px; height:200px; display:table; margin:20px auto; border:1px solid #ccc; position:relative;}
.txtbox div {display:table-cell; vertical-align:middle; text-align:center; *position:absolute; *top:50%;}
.txtbox div p{*position:relative; *top:-50%;}
</style>
</head>
<body>
<div class="imgbox">
<div><img src="http://placehold.it/50x50" alt=""></div>
</div>
<div class="txtbox">
<div>
<p>Doing this may not be as easy or obvious as we would hope.</p>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment