简体   繁体   English

使用纯CSS定位div

[英]Position div using pure css

This is a hard one to describe, but the fiddle shows what I want to do: 这很难描述,但是小提琴显示了我想做的事情:

https://jsfiddle.net/zbh8ewqg/ https://jsfiddle.net/zbh8ewqg/

I want to align the #inner div so that the top of the bottom div aligns with the top of the #outer div. 我想对齐#inner div,以便底部div的顶部与#outer div的顶部对齐。

Not to tricky using JavaScript, but can it be done in pure CSS? 使用JavaScript不是难事,但是可以在纯CSS中完成吗?

(Note: in practice the number of elements will be dynamic, and the height not known because, for example, the font may change, thus solutions with hard-coded numbers don't help. I'm not trying to transfer the calculation from JavaScript to my brain.) (注意:在实践中,元素的数量是动态的,高度未知,因为例如字体可能会更改,因此使用硬编码数字的解决方案无济于事。我并不是试图将计算从我的大脑是JavaScript。)

try to add this code. 尝试添加此代码。 It will give same output as mention on jsfiddle. 它将给出与jsfiddle相同的输出。

div#inner{
    position: absolute;
    top: -75px;
}

Not really sure what are you trying to achieve, because I would recommend changing the mark-up div arrangements. 不太确定您要实现什么目标,因为我建议您更改标记div安排。 But anyway, here is a pure css alternative: https://jsfiddle.net/x8f2os39/ 但是无论如何,这是一个纯CSS替代方法: https : //jsfiddle.net/x8f2os39/

enter code here

If you add to your div's a fixed line-height then it can be very easy to calculate what value for top you need. 如果您将div的固定line-height添加到div中,那么很容易计算出所需的top值。

If: 如果:

div {
    line-height:20px;
}

Then you just need to add top:-80px to your #inner div (4 divs above, 20px each) 然后,您只需要在#inner div中添加top:-80px (以上4个div,每个20px)

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM