首页 > 解决方案 > 如何计算居中 div 的顶部和左侧位置?

问题描述

这个问题比标题复杂一点,我试图获取使用这些 css 属性的居中 div 的顶部和左侧值:

top:50%;
left:50%;
transform:translate(-50%, -50%);

我能够毫无问题地获得顶部和左侧的值,但我不明白translate(-50%, -50%)下面论坛的行为方式。

尝试 Fiddle 进行测试:https ://jsfiddle.net/nqym3s4b/

...
<div id="div1">
    <div id="div2">...</div>
</div>

var div = document.querySelector('#div2');

var w = div.offsetWidth, 
    h = div.offsetHeight;

// top & left
var lw = (w / 100) * 50,
    lh = (h / 100) * 50;

// top & left with transform(-50%, -50%)
var tw = (lw / 100) * 50,
    th = (lh / 100) * 50;

left = 'left: ' + tw + 'px;';
top = 'top: ' + th + 'px;';

有任何想法吗?

标签: javascriptcsscss-transforms

解决方案


translate将考虑内部width元素的/ height,因此 50% 是已翻译元素的宽度/高度的一半,而/将考虑元素的尺寸。topleft

计算是两个值的简单相加(我添加了第三个 div#div2以便您可以看到结果)

var div1 = document.querySelector('#div1'); //parent element
var div2 = document.querySelector('#div2'); //translated element

var w1 = div1.offsetWidth,
    h1 = div1.offsetHeight;

var w2 = div2.offsetWidth,
    h2 = div2.offsetHeight;


var lw = (w1 / 100) * 50 + (-w2 / 100) * 50,
    lh = (h1 / 100) * 50 + (-h2 / 100) * 50;


document.querySelector('#left').innerHTML = 'left: ' + lw + 'px;';
document.querySelector('#top').innerHTML = 'top: ' + lh + 'px;';

document.querySelector('#div3').style.left = lw + 'px';
document.querySelector('#div3').style.top = lh + 'px';
#div1 {
  width: 560px;
  height: 240px;
  background: red;
  position: relative;
}

#div1 #div2 {
  width: 340px;
  height: 120px;
  background: yellow;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

#div1 #div3 {
  width: 50px;
  height: 50px;
  background: blue;
  position: absolute;
  opacity: 0.2;
}
<div id="div1">
  <div id="div2">
    <span id="left"></span>
    <br>
    <span id="top"></span>
  </div>
  <div id="div3">
    <!-- to compare -->
  </div>
</div>


推荐阅读