可能是重复问题:
如何水平垂直居中div
我需要将图像置于html页面的中心,无论是垂直还是水平...尝试了一些方法,但似乎效果不太好。为了实现水平对齐,我使用了
<body style="text-align:center">
它可以很好地工作,但是如何进行垂直对齐呢?
谢谢
可能是重复问题:
如何水平垂直居中div
我需要将图像置于html页面的中心,无论是垂直还是水平...尝试了一些方法,但似乎效果不太好。为了实现水平对齐,我使用了
<body style="text-align:center">
它可以很好地工作,但是如何进行垂直对齐呢?
谢谢
如果:
X 是图像宽度,
Y 是图像高度,
那么:
img {
position: absolute;
top: 50%;
left: 50%;
margin-left: -(X/2)px;
margin-top: -(Y/2)px;
}
但请记住,此解决方案仅在您的网站上唯一的元素是该图片时才有效。我想这里就是这种情况。
使用此方法可使图像具有流动性的优点。无论某人的屏幕有多大(或多小),图像始终会保持在中间。
margin-left
和 margin-top
行替换为以下内容:transform: translate(-50%,-50%);
- Fahri Azimov.imageContainer{
position: absolute;
width: 100px; /*the image width*/
height: 100px; /*the image height*/
left: 50%;
top: 50%;
margin-left: -50px; /*half the image width*/
margin-top: -50px; /*half the image height*/
}
现在你可以给标签设置背景图片,
并且像这样设置 background-position:center center;
就像这样:
body{
background:url('../img/some.jpg') no-repeat center center;
min-height:100%;
}
根据您所追求的效果,有许多不同的选择。Chris Coyier 曾经就这个问题写过一篇文章。值得一读:
display:table-cell
答案不同,并且带有未知尺寸的图像:https://dev59.com/q2TWa4cB1Zd3GeqPHuFG#10998683 - thirtydot