我倾向于在我设计的每个网站上都这样做,但我还没有真正找到一个真正好的方法来做到这一点。公司通常会向我提供他们的徽标,当您转到页面时,我将其置于屏幕中间,然后自动将您转到主页。我似乎无法找到一个好的方法来将图像置于屏幕中间,而不需要一堆表和div!有什么好建议吗?!
答案 0 :(得分:5)
您可以尝试在HTML中使用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%;
}
答案 1 :(得分:1)
就个人而言,我喜欢使用display: table-cell
方法。
例如,如果我的HTML是:
<div class="wrapper">
<img src="http://placehold.it/150x50" alt="Company ABC" />
</div>
然后我的CSS应该是:
div.wrapper {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 600px;
height: 200px;
}
如果我无法使用上述方法,另一个可行的选择是使用line-height
属性。
行高法的HTML:
<div class="wrapper">
<img src="http://placehold.it/150x50" alt="Company XYZ" />
</div>
行高法的CSS:
img {
line-height: 300px;
}
答案 2 :(得分:1)
您可以使用JavaScript计算中心点并使用margin或top(位置:relative / absolute)来定位它,但这不是很干净。
我假设你在谈论一个启动页面,所以这里有一个简单的例子(尽管在其他情况下我不建议像我一样修改body
标签):
<!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>
诀窍在于CSS:
display:table-cell
display:table
text-align:center
声明)和垂直对齐(vertical-align:middle
声明)text-align
和vertical-align
属性仅以此特殊方式运行,因为该元素显示为table-cell
答案 3 :(得分:1)
您没有说图像尺寸是否已知。
有几种方法可以做到这一点,我赞成使用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 */
}
答案 4 :(得分:1)
img {
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 */
}
&#13;
<body>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRMtBiLioXqfhufpptex_ta8kGJa5UDQS3aITpBetR8EwH5GGDTJw" />
</body>
&#13;
相关:Center a div