how can I not select last element of styled component

Viewed 5008

this is my code structure


const StyledArticle = styled.article``;

const StyledDiv = styled.div``; 

 <StyledArticle>
   <StyledDiv>1</StyledDiv>
   <StyledDiv>2</StyledDiv>  
   <StyledDiv>3</StyledDiv> 
   <StyledDiv>4</StyledDiv>  
 </StyledArticle> 

how can I add css StyledDiv 1,2,3 except 4th StyledDiv.

without add any css statement in StyledArticle

no js, jquery using only css.

2 Answers

You can use a combination of :not() and :last-of-type pseudo selectors:

StyledDiv:not(:last-of-type) {
  color: blue;
}
<StyledArticle>
  <StyledDiv>1</StyledDiv>
  <StyledDiv>2</StyledDiv>
  <StyledDiv>3</StyledDiv>
  <StyledDiv>4</StyledDiv>
</StyledArticle>

A styled component:

const StyledDiv = styled.div`
    &:not(:last-of-type) {
      color: red;
    }
`;

Use the CSS :not(:last-child) selector. It does exactly what it means. It selects elements that are not the last child of the parent.

<style> 
StyledArticle StyledDiv:not(:last-child) {
  background: red;
}
</style>
Related