所以,我已经看到很多关于此的问题,但我想要一个个人的例子。我对编程很新,所以我可能有点傻......
无论如何,我有两个<div>
,一个标识为bg
,另一个标识为player
。
这就是它的样子:
红色框是播放器,大图像是bg。
我需要玩家从bg的中心开始。
bg是640px X 640px。
这是我目前在CSS文件中的代码:
#bg {
width: 640px;
height: 640px;
top: 0;
left: 0;
}
.player {
position:relative;
background-color:#FF0000;
width: 32px;
height: 32px;
top: 0px;
left: 0px;
}
答案 0 :(得分:0)
尝试将样式表更改为:
#bg {
width: 640px;
height: 640px;
top: 0;
left: 0;
position: relative;
}
.player {
position: absolute;
background-color: #FF0000;
width: 32px;
height: 32px;
top: 320px;
left: 320px;
z-index: 1;
}
您的HTML应如下所示:
<div id="bg">
<!-- your bd code here -->
<div class="player"></div>
</div>
答案 1 :(得分:0)
position: relative
与正常放置物体的位置有关。在你的例子中,它通常会低于第一个div,因此它将保持不变。 (换句话说,与position: relative
定位一起使用的0
不会将对象移动到任何地方。)
您可以添加top: -320px; left: 320px
。这将它定位为第一个div的空间。但是maxksbd19的答案可能是您最终目标的更好解决方案。
答案 2 :(得分:0)
我尝试避免绝对定位,因为它不适应容器大小,并且更改容器需要您通过css并更改所有绝对值。
我会做以下
CSS:
#bg {
overflow: auto; /* stops the .player from from moving #bg down */
width: 640px;
height: 640px;
background-color: blue;
text-align: center; /* center child div in IE */
}
.player {
background-color: White;
width: 32px;
height: 32px;
margin: 0 auto; /* center div in parent for non IE browsers */
margin-top: 304px; /* 50% from top minus div size */
}
HTML:
<div id="bg">
<div class="player"></div>
</div>
现在您只需要跟踪子容器的上边距。