最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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
发布评论

评论列表(0)

  1. 暂无评论