Home > Software design >  ReactJS CSS inline style position dynamically
ReactJS CSS inline style position dynamically

Time:10-07

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

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

CodePudding user response:

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%)"
}}
  • Related