javascript - How can I get an element's width in px in styled-components? - Stack Overflow

Since the element can vary its width depending on the content it has, I don't know how to get its

Since the element can vary its width depending on the content it has, I don't know how to get its width in px.

Here is the basic, simplified, structure:

// React ponent 

export const Navbar = ({ month }) => (
  <NavbarStyled>
    <div>
      <span>{month}</span>  //month is what varies in width
    </div>
  </NavbarStyled>
)
// NavbarStyled.js

export const NavbarStyled = styled.nav`
  ...

  span:after{
    ...  

    animation: show 1s ease forwards;
  }

  @keyframes show{
    100%{
      transform: translateX(the_element's_width_in_px);
    }
  }
`

I've tried a lot of things with no results.

Thanks!

Since the element can vary its width depending on the content it has, I don't know how to get its width in px.

Here is the basic, simplified, structure:

// React ponent 

export const Navbar = ({ month }) => (
  <NavbarStyled>
    <div>
      <span>{month}</span>  //month is what varies in width
    </div>
  </NavbarStyled>
)
// NavbarStyled.js

export const NavbarStyled = styled.nav`
  ...

  span:after{
    ...  

    animation: show 1s ease forwards;
  }

  @keyframes show{
    100%{
      transform: translateX(the_element's_width_in_px);
    }
  }
`

I've tried a lot of things with no results.

Thanks!

Share Improve this question asked May 16, 2020 at 21:13 jmmjmm 1472 silver badges15 bronze badges 1
  • 1 What happens when you use the value 100%? – DannyXCII Commented May 16, 2020 at 21:45
Add a ment  | 

1 Answer 1

Reset to default 5

You can get the width by using the getBoundingClientRect() function, which will return an object of the element's attributes. With styled ponents, you will need to reference the element using the useRef hook or another referencing method in order to call getBoundingClientRect().

referencedElement.getBoundingClientRect()
// Return the width by calling referencedElement.getBoundingClientRect().width

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745193835a4615993.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信