的方法有多种,以下是其中几种常见的实现方式:
示例代码:
<div style="display: flex; justify-content: center; align-items: center; height: 200px; overflow: auto;">
<div style="margin: auto;">居中的元素</div>
</div>
示例代码:
<div style="display: grid; place-items: center; height: 200px; overflow: auto;">
<div style="margin: auto;">居中的元素</div>
</div>
示例代码:
<div id="scrollableDiv" style="height: 200px; overflow: auto;">
<div id="centeredElement">居中的元素</div>
</div>
<script>
const scrollableDiv = document.getElementById('scrollableDiv');
const centeredElement = document.getElementById('centeredElement');
scrollableDiv.addEventListener('scroll', () => {
const scrollableHeight = scrollableDiv.scrollHeight - scrollableDiv.clientHeight;
const centeredElementTop = (scrollableDiv.clientHeight - centeredElement.offsetHeight) / 2;
centeredElement.style.top = centeredElementTop + 'px';
});
</script>
以上是几种常见的使元素在可滚动的div中居中的方法,具体选择哪种方法取决于具体的需求和项目情况。
领取专属 10元无门槛券
手把手带您无忧上云