【问题标题】:how to use sibling selector css in styled如何在样式中使用兄弟选择器css
【发布时间】:2020-05-02 14:02:58
【问题描述】:

我有一个样式组件,看起来像:

import styled from 'styled-components';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';

export const CategoryList = styled(List)`
`;
//this is what i want to change
export const CategoryListItem = styled(ListItem)`
  border-top: 2px solid #f4f4f4;
`;

export const CategoryListItemText = styled(ListItemText)`
  padding-left: 5px;
`;

export const ListItemHeading = styled(ListItem)`
  background-color: #f4f4f4;
`;

在这种情况下如何使用兄弟姐妹 & + & ?

我想达到这样的目标:

li + li {
border-top: 1px solid red;
}

我怎样才能做到这一点?

【问题讨论】:

    标签: javascript css reactjs ecmascript-6 styled-components


    【解决方案1】:

    这与在 SCSS 中使用 & 的方式相同:

    export const CategoryListItem = styled(ListItem)`
      border-top: 2px solid #f4f4f4;
    
      & + & { // this will work for <CategoryListItem /><CategoryListItem />
        border-top: 1px solid red;
      }
    `;
    

    您也可以使用 html 元素设置样式,但上面的代码是更好的做法

    & + li { // this will work for <CategoryListItem /><li />
      border-top: 1px solid red;
    }
    

    基本上你可以用&amp;做任何嵌套

    & li { // this will work for <CategoryListItem><li /></CategoryListItem>
    }
    & li.test { // this will work for <CategoryListItem><li class="test" /></CategoryListItem>
    }
    

    您可以在官方文档中阅读它: https://styled-components.com/docs/basics#pseudoelements-pseudoselectors-and-nesting

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-02
    • 2011-12-13
    • 2017-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    相关资源
    最近更新 更多