如何抵消元素的第n个子元素 [英] How to offset the nth child of an element

查看:104
本文介绍了如何抵消元素的第n个子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试提取元素的第n个子元素,以便元素显示在同一个容器中。

I am trying to extract the nth child of an element, so that elements appear stacked within the same container.

我试过阅读 https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child ,但无济于事。

I've tried reading over https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child, but to no avail.

我在jsfiddle中重新创建了问题,

I recreated the problem in a jsfiddle,

https://jsfiddle.net/ndga732y/

html:

<table>
  <td>
    <p id="image-1">first content</p>
    <p id="image-2">second content</p>
  </td>
</table>

css:

p:nth-child(0n){
  offset-x: n*2px;
  offset-y: n*2px;
}

我知道使用nth-child选择器选择第n个孩子很容易,但是如何使用n值创建不同的偏移量,具体取决于它在容器中的顺序?

I understand that selecting the nth child is easy, using the nth-child selector, but how do I use the n-value to create a different offset, depending on its order in a container?

提前致谢!

推荐答案

遗憾的是,这对于普通的CSS是不可能的。

This isn't possible with plain CSS unfortunately.

你可以使用Javascript或CSS预处理器(也可能是后处理器?)。

You can use Javascript or a CSS preprocessor (probably a postprocessor as well?).

以下是我将如何使用Sass进行处理,它将编译为CSS:

Here is how I would approach it with Sass, which would compile to CSS:

@for $i from 1 through 2 {
  p:nth-child(#{$i}) {
    top: $i * 100px;
    left: $i * 50px;
    position: relative;
  }  
}

这是一个快速演示: http://www.sassmeister.com/gist/8af65851d1c404be698f

这篇关于如何抵消元素的第n个子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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