縦横の位置を計算

by ginpei

HTML

<p><button id="align">Aline</button></p>
<div id="wrapper">
  <div id="item">Item</div>
</div>

CSS

#wrapper {
  background-color: tomato;
  height: 300px;
  position: relative;
  width: 100%;
}
#item {
  background-color: skyblue;
  height: 100px;
  position: absolute;
  width: 100px;
}

JavaScript

const elWrapper = document.querySelector('#wrapper');
const elItem = document.querySelector('#item');
const elAlign = document.querySelector('#align');

elAlign.addEventListener('click', () => {
  [
    ['clientWidth', 'left'],
    ['clientHeight', 'top'],
  ].forEach(([sizeName, axisName]) => {
    const pos = (elWrapper[sizeName] - elItem[sizeName]) / 2;
    elItem.style[axisName] = `${pos}px`;
  });
});