Center Image Vertical and Horizontal
I tend to do this every web site I design I do, but I have yet to actually find a real good way to do it. A company usually gives me their logo, I center it in the middle of the screen for when you go to the page, and then it auto forwards you to the home page. I can not seem to find a good way to center an image in the middle of the screen without a bunch of tables and divs! Any good suggestions?!
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
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:
display:table-cell
display:table
text-align:center
declaration) and vertically ( vertical-align:middle
declaration) text-align
and vertical-align
properties only work this special way because the element is displayed as a table-cell
上一篇: 元素在一个div中的垂直对齐
下一篇: 居中图像垂直和水平