我倾向于在我设计的每个网站上都这样做,但我还没有真正找到一个真正的好方法来做到这一点。一家公司通常会给我他们的标志,我把它放在屏幕中间,当你进入页面时,它会自动将你转发到主页。如果没有一堆表格和 div,我似乎找不到将图像置于屏幕中间的好方法!有什么好的建议吗?!
5 回答
You could try using a div
in your HTML like this:
<div id='dv'></div>
And using a background image like this:
#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%;
}
Fiddle
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 */
}
<body>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRMtBiLioXqfhufpptex_ta8kGJa5UDQS3aITpBetR8EwH5GGDTJw" />
</body>
相关:将 div 居中
Personally, I like using the display: table-cell
method.
For example, if my HTML is:
<div class="wrapper">
<img src="http://placehold.it/150x50" alt="Company ABC" />
</div>
Then my CSS should be:
div.wrapper {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 600px;
height: 200px;
}
If I'm unable to use the above method, another viable option is to use the line-height
property.
HTML for line-height method:
<div class="wrapper">
<img src="http://placehold.it/150x50" alt="Company XYZ" />
</div>
CSS for line-height method:
img {
line-height: 300px;
}
You could use JavaScript to calculate the center point and position it with either margin or top (with position:relative/absolute), but this isn't really clean.
I'm assuming you're talking about a splash page, so here is a simple example (although in other circumstances I do not recommend modifying the body
tag as I have done):
<!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>
The trick is in the CSS:
- The item you wish to center both horizontally and vertically is displayed as a table cell:
display:table-cell
- The parent (container) of the item you wish to center is displayed as a table:
display:table
- Make sure the table display element is consuming the entire area which you would like to center against.
- The item you wish to center must be told to align horizontally (
text-align:center
declaration) and vertically (vertical-align:middle
declaration) - The
text-align
andvertical-align
properties only work this special way because the element is displayed as atable-cell
您不会说图像大小是否已知。
有几种方法可以做到这一点,我喜欢在图像上使用一些 CSS 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 */
}