I have created a card tracker for a game.
It is based on a grid pattern of different divs that overlay a background image. Within these divs are smaller images that represent the cards and can be dragged from one div to the next.
I would like the divs to scale with the window, but they need to retain their aspect ratio so that they still overlay the correct parts of the background image as that scales.
I can get this working using "padding-top" for the divs; however, this then makes the smaller appear at the very bottom of that div and extends the div, and prevents them being dragged out and I can't see why it has this effect.
Many thanks in advance for any help!
Here's an example div without padding-top applied:
#div33 {
position: absolute;
top: 250px;
left: 542px;
width: 270px;
height: 350px;
margin: 2px;
padding: 2px;
background-color: rgba(255, 184, 53, 0.);
}
The draggable elements:
.draggable {
padding: 0px;
background-color: rgba(255, 255, 255, 0);
cursor: move;
padding: 1px;
}
.draggable.dragging {
opacity: .1;
}
and the script for dragging and dropping:
<script>
const draggables = document.querySelectorAll('.draggable')
const containers = document.querySelectorAll('.container')
draggables.forEach(draggable => {
draggable.addEventListener('dragstart', () => {
draggable.classList.add('dragging')
})
draggable.addEventListener('dragend', () => {
draggable.classList.remove('dragging')
})
})
containers.forEach(container => {
container.addEventListener('dragover', e => {
e.preventDefault()
const afterElement = getDragAfterElement(container, e.clientY)
const draggable = document.querySelector('.dragging')
if (afterElement == null) {
container.appendChild(draggable)
} else {
container.insertBefore(draggable, afterElement)
}
})
})
function getDragAfterElement(container, y) {
const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')]
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect()
const offset = y - box.top - box.height / 2
if (offset < 0 && offset > closest.offset) {
return { offset: offset, element: child }
} else {
return closest
}
}, { offset: Number.NEGATIVE_INFINITY }).element
}
</script>
I think I have answered my own question. I've just found out about the newer "aspect-ratio" property.