【问题标题】:How to target the nth-of-type of an element using styled-components如何使用样式组件定位元素的第 n 个类型
【发布时间】:2021-05-18 05:18:20
【问题描述】:

我有这个styled-component。我想通过 css 和 styled-components 定位第二个 <Badge /> 但是我无法让它工作。我尝试了多种方法,但仍然卡住了。

//... maps through data and produces 2 cards with their title, price and discount (Badge)

        <CardContainerText>
          <CardTitle>{t(`${product.productName}`)}</CardTitle>{" "}
          <CardPrice>{t(`${totalPrice}€ / an`)}</CardPrice>
          {rate.amount > 0 && <Badge>Discount {rate.amount}% </Badge> }          </CardContainerText>
      </CardHeading>

这将产生以下html。

<div> CARD 1
  <h1>card title</h1>
  <p>card price</p>
  <span>card badge</span>
</div>
<div> CARD 2
  <h1>card title 2</h1>
  <p>card price 2</p>
  <span>card badge 2</span>
</div>

我想使用样式组件来定位卡片徽章 2,以便我可以正确设置它的样式。

我的&lt;Badge /&gt; css 看起来像这样:

export const Badge = styled.span`
  display: inline-block;
  position: relative;
  top: -233px;
  right: 61px;
  padding: 14px;
  transform: rotate(-45deg);

  @media (min-width: 740px) {
    top: -68px;
    right: 150px;
    padding: 8px;

  [ASK]: Here I want that the second badge has a different top position. But this does not work.
    &:nth-of-type(2n) {
      top: -95px;
    }
  }
`

【问题讨论】:

  • 我看不到第二个&lt;Badge /&gt;?你是说第二个&lt;CardContainerText&gt;里面的&lt;Badge /&gt;吗?
  • @MhdAlaaAlhaj 是的,第二个 &lt;Badge /&gt; 里面的第二个 &lt;CardContainerText /&gt; 没有看到这里,但是一旦我遍历它,我会得到 2 个 &lt;CardContainerText&gt; &lt;Badge /&gt; &lt;/CardContainerText&gt;

标签: css css-selectors styled-components


【解决方案1】:

您可能会有所不同:您希望第二个 CardContainerText 中的 Badge 具有不同的样式

export const Badge = styled.span`
  display: inline-block;
  position: relative;
  top: -233px;
  right: 61px;
  padding: 14px;
  transform: rotate(-45deg);

  @media (min-width: 740px) {
    top: -68px;
    right: 150px;
    padding: 8px;
  }
`;

const CardContainerText = styled.div`
  &:nth-of-type(2n) { /* this matches all even (2nd) CardContainerText */
    @media (min-width: 740px) {
      ${Badge} {  /* this matches the Badge in the 2nd container for yor media query */
        top: -95px;
      }
    }
  }
`;

这使用styled-components 能力到refer other components

【讨论】:

    【解决方案2】:

    您必须为徽章使用一个类。 像这样:

    @media screen and (max-width: 480px) {
      .container {
        width: 100vw;
      }
      .panel:nth-of-type(4),
      .panel:nth-of-type(5) {
        display: none;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-16
      • 2020-12-12
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      相关资源
      最近更新 更多