是否可以仅使用样式来相对于另一个动态调整大小的元素定位一个元素?
如果某些尺寸是动态的,是否可以仅使用 CSS 样式相对于另一个特定元素定位一个元素?
我知道我可以使用 jQuery 轻松做到这一点,但我正在尝试将所有内容都推入样式表中,而不是依赖 javascript。
下面的代码或多或少完成了我想要完成的任务,尽管我想摆脱 JavaScript 并且仍然具有相同的效果:
内容:
<div id="reference">
Some text - lorem ipsum, or short, shouldn't matter. See CSS
</div>
<div id="relative">
Relative
</div>
CSS:
div#reference {
min-height:200px; /* could be thousands of pixels */
width:500px;
padding:1em;
border-style:solid;
border-width:1px;
}
div#relative {
width:50px;
height:50px;
padding:1em;
background:orangered;
border-style:solid;
border-left-style:none;
border-width:1px;
}
JS:
var reference = $("div#reference");
var refPos = reference.offset();
var refWidth = reference.outerWidth();
var refHeight = reference.outerHeight();
var relative = $("div#relative");
var relHeight = relative.outerHeight();
relative
.css({
"position":"absolute",
"left":(refPos.left + refWidth) + "px",
"top":(refPos.top + refHeight - relHeight) + "px"
})
.show();
屏幕截图:
Is it possible to position one element relative to another specific element using only CSS styles if some of the dimensions are dynamic?
I know I can easily do this with jQuery, but I'm trying to push everything into the stylesheet that I possibly can rather than leaning on javascript.
Here is code that does more or less what I'm trying to accomplish, though I'd like to get rid of the javascript and still have the same effect:
Content:
<div id="reference">
Some text - lorem ipsum, or short, shouldn't matter. See CSS
</div>
<div id="relative">
Relative
</div>
CSS:
div#reference {
min-height:200px; /* could be thousands of pixels */
width:500px;
padding:1em;
border-style:solid;
border-width:1px;
}
div#relative {
width:50px;
height:50px;
padding:1em;
background:orangered;
border-style:solid;
border-left-style:none;
border-width:1px;
}
JS:
var reference = $("div#reference");
var refPos = reference.offset();
var refWidth = reference.outerWidth();
var refHeight = reference.outerHeight();
var relative = $("div#relative");
var relHeight = relative.outerHeight();
relative
.css({
"position":"absolute",
"left":(refPos.left + refWidth) + "px",
"top":(refPos.top + refHeight - relHeight) + "px"
})
.show();
Screenshot:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的。有很多方法可以做到这一点。您可以通过绝对定位来完成此操作,方法是将橙色方块放置在文本 div 中,并将其正确值设置为“-50px”,将其底部值设置为“0px”
,您的 HTML 如下所示:
尝试这样的操作。无论参考 div 的大小是多少,橙色方块都应始终位于底部和右侧。
Yes. There are many ways to do this. you can do it with absolute positioning by placing the orange square within your text div and set its right value to "-50px" and its bottom value to "0px"
and your HTML like this:
Try something like this. The orange square should stay at the bottom and to right at all times no matter what the size of the reference div is.