在CSS中设置button的position属性为absolute,并通过JavaScript动态计算按钮宽度、高度和容器的宽度、高度,最后通过设置top和left的值将按钮定位在容器的正中央。
HTML代码:
CSS代码:
.container {
position: relative;
}
button {
position: absolute;
}
JavaScript代码:
const button = document.querySelector('button');
const container = document.querySelector('.container');
const containerWidth = container.offsetWidth;
const containerHeight = container.offsetHeight;
const buttonWidth = button.offsetWidth;
const buttonHeight = button.offsetHeight;
button.style.top = (containerHeight - buttonHeight) / 2 + 'px';
button.style.left = (containerWidth - buttonWidth) / 2 + 'px';
下一篇:按钮不重定向