center align position absolute object horizontally

前端 未结 1 1302
野的像风
野的像风 2020-12-10 04:00

i have an element whose position is absolute the only issue i am facing is i have applied some properties to align it center horizontally and it is working fine on mozilla b

相关标签:
1条回答
  • 2020-12-10 04:48

    A useful trick to center elements is to use the transform: translate style together with either top, margin-left left or margin-top.

    To answer your question, you have to apply the following styles to your .slider a.downarrow element:

    left: 50%;
    transform: translateX(-50%);
    

    The way this works is because if translate is used with a percentage value, its value is calculated based on the elements height/width on which it is applied on.

    top, margin-left left and margin-top percentage values are calculated based on the parent element or in case the element has position: absolute applied to it based on the nearest parent with position: relative/absolute.

    To center an element you just need to apply a value of 50% to either top, margin-left left or margin-top and a value of -50% to translate.

    For left and margin-left you have to use translateX(-50%) and for the others translateY(-50%).

    EDIT: Added an explanation

    0 讨论(0)
提交回复
热议问题