Position by center point, rather than top-left point

后端 未结 6 2085
鱼传尺愫
鱼传尺愫 2021-02-01 01:14

Is it possible to tell the code to position by the center point of an element, rather than by the top-left point? If my parent element has

width         


        
6条回答
  •  不思量自难忘°
    2021-02-01 01:22

    left:50% doesn't center the center of gravity of this div 50% to the left, it is the distance between the left border and the left border of the parent element, so basically you need to do some calculations.

    left = Width(parent div) - [ Width(child div) + Width(left border) + Width(right border) ]
    
    left = left / 2
    

    So you can do a Javascript function...

    function Position(var parentWidth, var childWith, var borderWidth)
    {
          //Example parentWidth = 400, childWidth = 200, borderWidth = 1
          var left = (parentWidth - ( childWidth + borderWidth));
          left = left/2;
          document.getElementById("myDiv").style.left= left+"px";
    }
    

提交回复
热议问题