javascript - 如何在样式中使用同级选择器 css

标签 javascript css reactjs ecmascript-6 styled-components

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

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;
`;

在这种情况下如何使用 sibling & + & ?

我想实现这样的目标:

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

我怎样才能做到这一点?

最佳答案

这与在 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;
}

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

& 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

关于javascript - 如何在样式中使用同级选择器 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59757602/

相关文章:

javascript - 使用选择框突出显示匹配的 html 单元格

html - Css背景图片位置问题

html - 居中 <p> 不设置宽度

javascript - 我如何减少图表 js 圆环图的边框宽度

javascript - Jquery仅切换单击的div下的p标签

: 65 or 97? 的 Javascript 键码

javascript - 使用 useState() 将对象作为状态

javascript - 读取两个输入字符串并连接它们

php - 文件上传请求中的 Content-Transfer-Encoding

css - Bootstrap 4 和 css 变换旋转