Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ReactJS CSS inline style position dynamically

I have this element in my React code:

{focusedAnnotationIconProps && (
                    <div
                        style={{
                            backgroundColor: "#333",
                            width: "100px",
                            position: "absolute",
                            left: focusedAnnotationIconProps.left,
                            top: focusedAnnotationIconProps.top + 25,
                            color: "#fff",
                        }}
                    >
                        {annotationIconPopoverText}
                    </div>
                )}

this is a popover that will show when hovering over an icon, so I get the CSS left/top position numbers from that Icon (in another part of the code), and place it there, and currently, is showing like this:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I need to center this popover in the middle of the icon
but the thing is, this <div> element has variable width, depending on the text inside
so I was thinking of someway to do something like this:

left: focusedAnnotationIconProps.left - this.width/2

but I know that won’t work.. I tried using the calc css3 function, but won’t work inline with CSS, so there’s my problem.. would appreciate any help

>Solution :

With position: absolute, you can use these methods to center the elements:

Center Vertically:

style={{
  top: "50%",
  transform: "translateY(-50%)"
}}

Center Horizontally:

style={{
  left: "50%",
  transform: "translateX(-50%)"
}}

Center to the parent div:

style={{
  left: "50%",
  top: "50%",
  transform: "translate(-50%, -50%)"
}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading