使用CSS(水平和垂直)居中图像 [英] Center an image with CSS (horizontal and vertical)
问题描述
这是一个我无法找到答案的基本问题。
我想采取一个标志图像,它正好位于屏幕中间,当保持图像在其原始大小。
比这个图像正下方( - 5px下),放一个小文本行,我选择它的字体。
当我试图这样做,所以我会把基本的,如果你可以帮助我实现这个简单的目标,这将是巨大的。
< html>
< body>
< img src =images / logoBlackBig.pngalt =W3Schools.com>
< / body>
< / html>
改进 - 现在已调整图片大小
构建块
-
图像和文本包装在div中。
-
由于正确的组合
位置:绝对
,left和margin:auto
。 -
容器将重新调整为其最大宽度和高度
height:100%
和width:100%
-
max-height:100%
和max-width:100%
确保图像宽高比重新调整大小时保持1:1。
IE 8需要容器的固定像素高度。
更改最大宽度和高度以匹配图片。
演示
* {margin:0; padding:0;}。centered {position:absolute; top:-4em; / *更改顶部单位大小以获得所需的垂直放置* /右:0; bottom:0; left:0; margin:auto;高度:100%; / * IE 8需要px高度* / width:100%; max-height:300px; max-width:300px; min-width:100px; text-align:center;}。居中img {max-height:100%; max-width:100%; min-width:100px;}
< div class = centered> < img src =http://www.placehold.it/300/> < h1>绿蛋和火腿< / div>
This is a basic question that i couldn't find answer to .
I would like to take a logo image, centre it exactly in the middle of the screen ,when keeping the image in its original size . Than right under that image(- 5px down), put a small text line, where i choose its font .
Everything is messed up when i am trying to do that , so i will put the basic ,and if you can help me achieve this simple goal, that would be great .
<html>
<body>
<img src="images/logoBlackBig.png" alt="W3Schools.com" >
</body>
</html>
Improved - now with image re-sizing
Building Blocks
The image and text are wrapped in a div.
The div is centered thanks to the right combination of
position: absolute
, top, right, bottom, left andmargin: auto
.The container will re-size to its max width and height with
height: 100%
andwidth: 100%
max-height: 100%
andmax-width: 100%
ensures that the image width height ratio remains 1:1 when re-sizing.
IE 8 needs a fixed pixel height for the container.
Change max width and height to match the image.
Demo
* {
margin: 0;
padding: 0;
}
.centered {
position: absolute;
top: -4em;
/* change top unit size to get desired vertical placement */
right: 0;
bottom: 0;
left: 0;
margin: auto;
height: 100%; /*IE 8 Needs px height */
width: 100%;
max-height: 300px;
max-width: 300px;
min-width: 100px;
text-align: center;
}
.centered img {
max-height: 100%;
max-width: 100%;
min-width: 100px;
}
<div class="centered">
<img src="http://www.placehold.it/300" />
<h1>Green Eggs and Ham</h1>
</div>
这篇关于使用CSS(水平和垂直)居中图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!