BoundingClientRectは、要素の寸法とビューポートとの相対的な位置に関する情報になります。
情報には、要素の寸法(パディングと境界線を含む大きさ)であるwidthとheight と要素の位置である left / x、top / y、right、bottom が含まれています。
$element.getBoundingClientRect()$
要素の寸法と、ビューポートに対する相対位置に関する情報( DOMRectオブジェクト )を返します。
<body>
<div class="container">
<div class="box">
<p>BoundingClientRectの情報を表示</p>
</div>
</div>
</body>
html, body {
width: 100%;
height: 100%;
}
html {
box-sizing: border-box;
font-size: 62.5%;
}
body {
margin: 0;
padding: 0;
}
*, *::before, *::after {
box-sizing: inherit;
}
.container {
position: relative;
height: 100%;
}
.box {
position: absolute;
top: calc( 50% - ( 400px / 2 ) );
left: calc( 50% - ( 350px / 2 ) );
display: flex;
justify-content: center;
align-items: center;
width: 350px;
height: 400px;
background: skyblue;
p {
font-size: 1.4rem;
font-weight: bold;
}
}
const box = document.querySelector( ".box" );
const p = box.querySelector( "p" );
const boxRect = box.getBoundingClientRect();
let boxRectText = JSON.stringify( boxRect );
boxRectText = boxRectText.replace( /["{}]/g, "" );
boxRectText = boxRectText.replace( /:/g, ":" );
boxRectText = boxRectText.replace( /\\,/g, "<br>" );
p.innerHTML = boxRectText;