HTML 位置 = center-10px
HTML position = center-10px
我正在制作一个 HTML 网站。我有一张地图作为背景图片,我需要一个按钮才能出现在地图上。像这样:
但是当我开始扩展我的网站时,会发生这种情况:
我知道是什么问题了:图片的位置是center-X px
和center-Y px
,不是margin: 40% 0px 0px 20%
。但是怎么做呢? position: absolute; left: 50%-30px; top: 50%-83px
不起作用。
您需要图像相对于背景图像(div 以地图作为背景图像的容器):
position: relative; left: 30px; top: 83px
您可以使用比calc()
支持更好的负边距。
position: absolute;
left: 50%;
top: 50%;
margin-top: -83px;
margin-left: -30px;
如果您已经有边距,您可以从那里减去它们。但是,如果它们被定义为百分比或 em
,那么您将不得不相应地转换它们。
很多人提到使用绝对边距(这会起作用),但是 transform: translate
的实现还有另一种方法。
在下面的示例中,内部 img
始终位于其包含 div 的中心,我相信这也能满足您的需求。我还在盒子里添加了一些随机动画,这样你就可以看到它自己定位的效果如何。
setInterval(randomAnimation, 500);
function randomAnimation() {
var random = Math.floor(Math.random() * (4 - 0));
if (random == 0)
$(".box").animate({
top: "+=50"
});
else if (random == 1)
$(".box").animate({
left: "+=50"
});
else if (random == 2)
$(".box").animate({
top: "-=50"
});
else
$(".box").animate({
height: "+=50"
});
}
.box {
position: relative;
width: 150px;
height: 100px;
background-image: url(http://via.placeholder.com/150x100/ff0000/ffffff)
}
img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<img src="http://via.placeholder.com/50x50" />
</div>
我正在制作一个 HTML 网站。我有一张地图作为背景图片,我需要一个按钮才能出现在地图上。像这样:
但是当我开始扩展我的网站时,会发生这种情况:center-X px
和center-Y px
,不是margin: 40% 0px 0px 20%
。但是怎么做呢? position: absolute; left: 50%-30px; top: 50%-83px
不起作用。
您需要图像相对于背景图像(div 以地图作为背景图像的容器):
position: relative; left: 30px; top: 83px
您可以使用比calc()
支持更好的负边距。
position: absolute;
left: 50%;
top: 50%;
margin-top: -83px;
margin-left: -30px;
如果您已经有边距,您可以从那里减去它们。但是,如果它们被定义为百分比或 em
,那么您将不得不相应地转换它们。
很多人提到使用绝对边距(这会起作用),但是 transform: translate
的实现还有另一种方法。
在下面的示例中,内部 img
始终位于其包含 div 的中心,我相信这也能满足您的需求。我还在盒子里添加了一些随机动画,这样你就可以看到它自己定位的效果如何。
setInterval(randomAnimation, 500);
function randomAnimation() {
var random = Math.floor(Math.random() * (4 - 0));
if (random == 0)
$(".box").animate({
top: "+=50"
});
else if (random == 1)
$(".box").animate({
left: "+=50"
});
else if (random == 2)
$(".box").animate({
top: "-=50"
});
else
$(".box").animate({
height: "+=50"
});
}
.box {
position: relative;
width: 150px;
height: 100px;
background-image: url(http://via.placeholder.com/150x100/ff0000/ffffff)
}
img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<img src="http://via.placeholder.com/50x50" />
</div>