我在设计每个网站时都会这样做,但是我还没有找到一个真正好的方法来实现它。通常公司会给我他们的标志,我会将它居中放置在页面中央,然后自动转到主页。我似乎找不到一个好的方法来将图像居中放置在屏幕中央,而不需要使用大量的表格和div!有什么好建议吗?
我在设计每个网站时都会这样做,但是我还没有找到一个真正好的方法来实现它。通常公司会给我他们的标志,我会将它居中放置在页面中央,然后自动转到主页。我似乎找不到一个好的方法来将图像居中放置在屏幕中央,而不需要使用大量的表格和div!有什么好建议吗?
div
,如下所示:<div id='dv'></div>
并且使用像这样的背景图片:
#dv {
background: url('http://pieisgood.org/images/slice.jpg') no-repeat 0 0;
background-position: center;
}
html,body,#dv { /* so that the #dv can fill up the page */
width:100%;
height:100%;
}
background-size: 400px 300px;
。 - tckmnimg {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%); /* IE 9 */
-webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */
}
<body>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRMtBiLioXqfhufpptex_ta8kGJa5UDQS3aITpBetR8EwH5GGDTJw" />
</body>
Related: Center a div
个人而言,我喜欢使用display: table-cell
方法。
例如,如果我的HTML代码是:
<div class="wrapper">
<img src="http://placehold.it/150x50" alt="Company ABC" />
</div>
div.wrapper {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 600px;
height: 200px;
}
line-height
属性。<div class="wrapper">
<img src="http://placehold.it/150x50" alt="Company XYZ" />
</div>
CSS的行高方法:
img {
line-height: 300px;
}
<!doctype html>
<html>
<head>
<title>blah</title>
<style type="text/css">
html,body {margin:0;padding:0;width:100%;height:100%;}
body {display:table;}
p {display:table-cell;text-align:center;vertical-align:middle;}
</style>
</head>
<body>
<p>Hello World - This could have an image in it</p>
</body>
</html>
display:table-cell
display:table
text-align:center
声明)和垂直对齐(vertical-align:middle
声明)text-align
和vertical-align
属性之所以以这种特殊方式工作,是因为该元素显示为table-cell
id="centreme"
的图像上(如果图像为200x200),以及整个页面的包装器。div#contentwrapper {
width:100%;
height:100%;
position:relative;
}
img#centreme {
position: relative;
width: 200px; /* the image width */
height: 200px; /* the image height */
top: 50%;
left: 50%;
margin-top: -100px; /* half the image height */
margin-left:-100px; /* half the image width */
}
这里有一个供您玩耍的 fiddle http://jsfiddle.net/7PYzB/2/