的方法有多种,以下是其中几种常见的实现方式:
示例代码:
<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中居中的方法,具体选择哪种方法取决于具体的需求和项目情况。
在网页上使 HTML 元素居中看似一件很简单的事情. 至少在某些情况下是这样的,但是复杂的布局往往使一些解决方案不能很好的发挥作用。
在网页布局中元素水平居中比元素垂直居中要简单不少,同时实现水平居中和垂直居中往往是最难的。现在是响应式设计的时代,我们很难确切的知道元素的准确高度和宽度,所以一些方案不大适用。据我所知, 在CSS中至少有六种实现居中的方法。我将使用下面的HTML结构从简单到复杂开始讲解:
领取专属 10元无门槛券
手把手带您无忧上云