网页input box无法居中:我的代码为何无法实现居中效果?
问题原因及解决方法
为什么input无法居中?
- 你用
position: absolute定位时,top:50%和right:50%是把input的右上角对齐到了父元素的中心,而不是让input自身的中心与页面中心重合,这直接导致了偏移。 - 另外,你的
body没有设置高度,默认高度仅由内部内容撑开,所以top:50%是相对于body的高度(也就是input的高度)计算的,而非整个浏览器视口的50%,进一步加剧了定位偏差。
解决方案
方案一:修正绝对定位
调整input的定位逻辑,同时让body占满视口:
@import url("https://fonts.googleapis.com/css?family=Ubuntu"); body { background-color: black; margin: 0; /* 清除浏览器默认margin */ height: 100vh; /* 让body高度等于视口高度 */ } #textInput { position: absolute; top: 50%; left: 50%; /* 将right改为left,定位到视口水平中心 */ width: 300px; transform: translate(-50%, -50%); /* 向左、向上移动自身宽高的50%,实现中心对齐 */ }
方案二:使用Flex布局(更简洁推荐)
抛弃绝对定位,利用flex布局快速实现居中:
@import url("https://fonts.googleapis.com/css?family=Ubuntu"); body { background-color: black; margin: 0; height: 100vh; display: flex; justify-content: center; /* 水平方向居中 */ align-items: center; /* 垂直方向居中 */ } #textInput { width: 300px; }
内容的提问来源于stack exchange,提问作者Anonymous
相关产品推荐
相关产品推荐

