【问题标题】:How to display a gif in the middle of a div page in jQuery?如何在 jQuery 的 div 页面中间显示 gif?
【发布时间】:2014-05-25 20:18:46
【问题描述】:
我有一个 div,它作为一个页面,它只有一个 gif。虽然 gif 出现在页面的左上角。我想让它出现在页面中间。您可以在下面找到我尝试过的 HTML 和 CSS,但它似乎不起作用。
<div id="correctGIF" data-role="page" data-add-back-btn="false">
<img src="images/correct.gif">
</div>
.correctGIF > img {
position: absolute;
left: 50%;
top: 50%;
}
【问题讨论】:
标签:
javascript
jquery
html
css
【解决方案1】:
假设你的 div 是页面大小并且有position:relative 那么
#correctGIF > img {
position: absolute;
left: 50%;
top: 50%;
display:block;
}
将为您提供大部分的帮助。
但是,它的作用是将图像的左上角/左角放在 50% 的位置,因此它不是完全居中的。
如果你知道图像的大小,你可以像这样用负边距调整它
margin-top: - [Insert 50% of image height] px;
margin-left: - [Insert 50% of image width] px;
所以,例如
margin-top: -100px;
margin-left: -100px;
对于 200x200 的图像。
如果您不知道图像的大小(也许您会经常更改它),那么您可以省去负边距并直接使用。
transform: translate(-50%, -50%);
这会根据图像的 OWN 尺寸调整图像的最终位置,而不管它们可能是什么。
【解决方案2】:
您在 css 中使用类选择器而不是 id 选择器。
您可以将其更改为 id 选择器:
#correctGIF > img {
position: absolute;
left: 50%;
top: 50%;
}
或者,您可以对 div 应用样式以显示为表格并将其居中:
<div style="display:table-cell; vertical-align:middle; text-align:center" data-role="page" data-add-back-btn="false">
<img src="images/correct.gif">
</div>
【解决方案3】:
错误的 CSS 选择器
#correctGIF > img {
position: absolute;
left: 50%;
top: 50%;
}