Search code examples
cssreactjsstyled-components

Border Second and Third Dropdown Only in React


I wanted to put a border line on top the second and third dropdown only. I still cant achieve it. CLICK HERE

const Select = styled.select`
  width: 100%;
  min-width: 0px;
  outline: 2px solid transparent;
  outline-offset: 2px;
  position: relative;
  appearance: none;
  background: inherit;
  padding-inline-start: 3rem;
  padding-inline-end: 2rem;
  height: 3.2rem;
  &:nth-child(1),
  :nth-child(3) {
    border: none;
  }
  border: 1px solid;
  border-left: none;
  border-right: none;
  border-color: #cecece;
`;

Solution

  • The main problem is, you're using nth-child(1) so, it'd apply on the select children but not on the select by itself.

    The recommended modifier in this case would be apply directly on the element, in that case I'd say nth-of-type.

    &:nth-of-type(1) {
      background: red;
    }
    

    But the main problem with that one is ALL the elements have to be at the same level or the query has to be part of the grandparent.

    So, in your code would work in this way:

    const Item = styled.div`
      margin: 0.2rem 0;
    
      &:nth-of-type(2) select,
      &:nth-of-type(3) select {
        background: blue;
      }
    `;
    

    Also, Taking advantage of styled-components. I included the index props. And use to include the border or not in your style. It's like:

    const Select = styled.select`
      width: 100%;
      min-width: 0px;
      outline: 2px solid transparent;
      outline-offset: 2px;
      position: relative;
      appearance: none;
      background: inherit;
      padding-inline-start: 3rem;
      padding-inline-end: 2rem;
      height: 3.2rem;
      border: ${props => props.index && [1, 2].includes(props.index) ? '1px solid #cecece' : 'none'};
      border-left: none;
      border-right: none;
      border-bottom: none;
    `;
    

    I have forked your codepen, here you have both approaches working:

    • With index
    • recommended With grandparent query (this approach is using background)

    https://codesandbox.io/s/dropdown-styled-components-forked-vpo6k?file=/src/index.js:285-366