绝对*在*另一个元素内定位一个元素 [英] positioning an element absolutely *within* another element

查看:108
本文介绍了绝对*在*另一个元素内定位一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该问题转到css向导.我已经用谷歌搜索了,找不到答案. 在这一点上,我不确定是否有可能:

可以这么说半确定如何在另一个元素中指定一个元素的位置?

我想说无论外部发生在哪里,都将元素内部 x像素放置在外部左边框的右侧在此刻."

使用javascript可能可以实现,但是使用CSS不能吗?

解决方案

#inner {
    position: absolute;
    left: 10px;
}

此CSS实际执行的操作是将#inner元素放置在距离其最近"父对象的左边界10px处,其位置值为absoluterelativefixed.如果找不到这样的元素,则它相对于body元素是绝对定位的,但是如果您确保内部元素的父元素的位置由CSS定义,则它将绝对位于该父元素内.

看看这个JSFiddle. 首先,看一下html和CSS来查看其构造方式,然后继续并使用鼠标拖动任一元素(这就是javascript中所做的事情,纯粹是出于演示目的).请注意,当拖动外部元素时,内部元素如何随之移动?拖动元素时,您所做的全部工作就是更改其topleft属性的值,并且由于其父元素是绝对位置,因此无论您将其移动到何处,子元素都将停留在同一位置屏幕上. :D

This question goes to the css wizards. I've googled this and couldn't find an answer. At this point I'm not sure it's possible:

How do I specify the position of an element within another element, semi-absolutely so to speak?

I want to say "Put element inner x pixels to the right of outer's left border, no matter where outer happens to be at the moment."

This might be possible with javascript, but shouldn't it be possible with css?

解决方案

#inner {
    position: absolute;
    left: 10px;
}

What this CSS actually does is position the #inner element 10px from the left border of its 'closest' parent that is has a position value of absolute, relative, or fixed. If no such element is found, it is absolute positioned relative to the body element, but if you make sure that the inner element has a parent that has its position defined with CSS, it will be positioned absolutely within that parent.

Take a look at this JSFiddle. First, look at the html and CSS to see how it was constructed, then go ahead and use your mouse to drag either of the element around (that's what the javascript in their does, its purely for demonstration purposes). Notice how when you drag the outer element, the inner one moves with it? All you are doing when you drag the elements around is changing the values of their top and left properties, and since its parent is absolute positioned, the child element will stay at the same spot within it no matter where you move it on the screen. :D

这篇关于绝对*在*另一个元素内定位一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆