When elements are laid out using flexbox, I'd like to know what their top and left is relative to the window.
Is this possible?
Using window.getComputedStyle
returns auto
for both top
and left
properties.
const cells = document.querySelectorAll('.cell')
cells.forEach(cell => {
cell.addEventListener('click', function(event) {
const cell = event.target;
const left = getComputedStyle(cell).left;
const top = getComputedStyle(cell).top;
document.getElementById('display').innerHTML = 'Left: ' + left + ' - Top: ' + top;
});
})
.container {
display: flex;
flex-direction: column;
height: 100vh;
width: 50vh;
margin: 0 auto;
justify-content: center;
align-items: center;
}
.container .row {
display: flex;
}
:root {
--cell-size: 20px;
}
.container .row .cell {
width: var(--cell-size);
height: var(--cell-size);
background-color: steelblue;
border: 1px #ccc solid;
border-radius: 100%;
margin: calc(var(--cell-size) / 4);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Animation demo</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div>Click a flex child to see its computed top and left</div>
<div id="display"> </div>
<div class="row">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
</div>
</body>
</html>