0

How can I change width StyledLi::after from 0% to 90%, after hover on StyledLink

const StyledLink = styled(Link)`
    text-decoration: none;
    margin-right: 20px;
    font-size: 20px;
    color: grey;
    transition: 0.2s;

    :hover {
        color: blue;
    }
`
const StyledLi = styled.li`
    ::after {
        content: "";
        display: block;
        width: 0%;
        height: 2px;
        background-color: blue;
    }
`
Vuzii
  • 75
  • 8
  • What's the HTML markup ? It'd be helpful to see it – AdamKniec Nov 18 '19 at 14:11
  • Seeing the HTML markup is more than just _helpful_ here, it is _necessary_. You can only do this, if StyledLi is either a following sibling of StyledLink (or contained within one), or contained within StyledLink itself. – 04FS Nov 18 '19 at 14:12
  • Aditionally: it might be a good idea to take a look here -> https://stackoverflow.com/questions/6910049/on-a-css-hover-event-can-i-change-another-divs-styling :) – AdamKniec Nov 18 '19 at 14:14
  • Take a look to: https://www.styled-components.com/docs/advanced#referring-to-other-components – Deve Nov 18 '19 at 16:38

1 Answers1

0

Try this. You can use absolute positioning. Set relative position for StyledLi and absolute position for :after in StyledLink.

Second variant, use pseudo element for StyledLi and hover for StyledLi.

You can see two examples below.

const Container = styled.div``;

const List = styled.ul``;

const StyledLi = styled.li`
  position: relative;
`;

const StyledLink = styled.a`
  text-decoration: none;
  margin-right: 20px;
  font-size: 20px;
  color: grey;
  transition: 0.2s;

  :after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;
    display: block;
    width: 0%;
    height: 2px;
    background-color: blue;
  }

  :hover {
    color: blue;
  }

  :hover:after {
    width: 90%;
  }
`;

const App = () => (
  <Container>
    <List>
      <StyledLi>
        <StyledLink>List Item</StyledLink>
      </StyledLi>
      <StyledLi>
        <StyledLink>List Item</StyledLink>
      </StyledLi>
      <StyledLi>
        <StyledLink>List Item</StyledLink>
      </StyledLi>
    </List>
  </Container>
);

Second variant

const Container = styled.div``;

const List = styled.ul``;

const StyledLi = styled.li`
  color: grey;

  :after {
    content: "";
    bottom: 0;
    left: 0;
    display: block;
    width: 0%;
    height: 2px;
    background-color: blue;
  }

  :hover:after {
    width: 90%;
  }

  :hover {
    color: blue;
  }
`;

const StyledLink = styled.a`
  text-decoration: none;
  margin-right: 20px;
  font-size: 20px;
  transition: 0.2s;
  color: inherit;
`;

const App = () => (
  <Container>
    <List>
      <StyledLi>
        <StyledLink>List Item</StyledLink>
      </StyledLi>
      <StyledLi>
        <StyledLink>List Item</StyledLink>
      </StyledLi>
      <StyledLi>
        <StyledLink>List Item</StyledLink>
      </StyledLi>
    </List>
  </Container>
);
Ivan Popov
  • 656
  • 2
  • 10