CSS 左边的相对位置有效,但顶部不起作用



我试图在任意容器中任意放置任意元素。我想指定一个百分比位置,其中

  • 0%的意思是"左边缘与容器的左侧对齐"。
  • 100%的意思是"右边缘与容器的右边缘对齐"。
  • 介于两者之间的任何值都是线性插值的,因此50%将是"中间对齐与中间对齐">

为此,容器具有position: relative;.元素具有position: absolute;lefttop等于百分比 - 这些百分比将相对于容器的大小。然后,元素的内容以position: relative;left向后移动,top等于负百分比,因为这将相对于元素的大小。

演示:

#container {
position: relative;
width: 200px;
height: 150px;
background-color: #cfc;
}
#item {
position: absolute;
left: 80%;
top: 80%;
background-color: #fcc;
}
#item>img {
position: relative;
display: block;
left: -80%;
top: -80%;
}
<div id="container">
<div id="item">
<img src="//placehold.it/100x100" />
</div>
</div>

在演示中,绿色框是容器,红色框是元素的"真实"位置,而占位符图像是实际内容。此处使用的坐标(80%,80%)使其显示在右下角。

如您所见,left组件工作正常。这正是它应该在的地方。然而,top并没有做"后移"的事情。它一点也不动。

当然有很多类似的问题,但我看到的所有问题都源于"相对于"元素是relative元素,而不是absolute,这意味着容器的高度为零 - 足够公平。事实上,在演示中的红色框中明确设置height可以解决问题。但是,我有没有提到这些组件的任意性?我无法明确设置元素的高度,我需要它根据内容而变化,这可能会动态变化。

任何想法我该怎么做?

如前所述,这里的主要问题是,只有当父项指定了高度时,带有百分比值的top才有效,而这里的情况并非如此。因此,为了解决此问题,我们需要找到一种方法来为item提供与其内容高度相等且不同于auto的指定高度。

我们的想法是考虑#item内的另一个div,并使这个容器成为一个灵活的容器。这将使新div被拉伸并指定高度(是的,flex 是魔术(,因此img上的top值将正常工作。

#container {
position: relative;
width: 200px;
height: 150px;
background-color: #cfc;
overflow:hidden;
}
#item {
position: absolute;
display:flex;
animation: change-1 1s linear infinite alternate;
}
#item img {
position: relative;
display: block;
animation: change-2 1s linear infinite alternate;
}
@keyframes change-1 {
from {
top:0%;
left:0%;
}
to {
top:100%;
left:100%;
}
}
@keyframes change-2 {
from {
top:0%;
left:0%;
}
to {
top:-100%;
left:-100%;
}
}
<div id="container">
<div id="item">
<div>
<img src="//placehold.it/100x100" >
</div>
</div>
</div>

在这里你可以使用transform属性来占位符,并为x和y坐标赋予相同的值,即-80%。 希望这对您有所帮助。

#container {
position: relative;
width: 200px;
height: 150px;
background-color: #cfc;
}
#item {
position: absolute;
left: 80%;
top: 80%;
background-color: #fcc;
}
#item>img {
position: relative;
display: block;
transform: translate(-80%,-80%);
}
<div id="container">
<div id="item">
<img src="//placehold.it/100x100" />
</div>
</div>

您应该指定父元素的高度:)


更新您还可以尝试为img设置负margin-top: -80%而不是top: 80%,并设置margin-bottom: 80%以保留父元素高度:

#container {
position: relative;
width: 200px;
height: 150px;
background-color: #cfc;
}
#item {
position: absolute;
left: 80%;
top: 80%;
background-color: #fcc;
}
#item>img {
position: relative;
display: block;
left: -80%;
margin-top: -80%;
margin-bottom: 80%;
}
<div id="container">
<div id="item">
<img src="//placehold.it/100x100" />
</div>
</div>

唯一的技巧是百分比边距相对于父元素宽度进行设置,因此,显然,如果您没有方形图像,它将无法正常工作。

我已经通过让 JavaScript 根据内容的像素大小设置margin-leftmargin-top来"解决"这个问题,并为窗口大小调整和内容更改添加了事件处理程序。虽然这有效,但我不喜欢它。到目前为止,仅CSS解决方案将胜过这一点。

最新更新