如何让.timedisplay容器内的内容在页面中居中对齐?
问题:实现.timedisplay容器内容在页面居中对齐
我编写了如下HTML与CSS代码,希望让.timedisplay容器内的内容在页面中居中对齐,但对CSS不太熟悉。目前采用margin-left:40.8%的临时方案,尝试过各类align center属性和margin:auto,但内容始终靠左,求.timedisplay的正确CSS写法。
原有代码
CSS代码
.timedisplay { display: inline-flex; margin-left: 40.8%; } .input1 { border-style: hidden; font-size: 150px; margin-top: none; padding: 0px; max-width: fit-content; font-family: "Times New Roman", Times, serif; width: 150px; height: fit-content; color: #940e0e; background-color: #0f2f5f; } .colon { font-size: 150px; color: #940e0e; margin-top: 0px; margin-bottom: 0px; } input[type="text"]:disabled { background: none; user-select: none; margin-top: none; }
HTML代码
<div class="timedisplay"> <input class="input1" id="input1" type="text" onfocus="clearInput(this)" onblur="unclearInput2(this)" id="minuter" autocomplete="off" maxlength="2" value="00" onkeypress="return event.charCode >= 48 && event.charCode <= 57" /> <p class="colon">:</p> <input class="input1" id="input2" type="text" onfocus="clearInput(this)" onblur="unclearInput(this)" id="sekunder" autocomplete="off" maxlength="2" value="00" onkeypress="return event.charCode >= 48 && event.charCode <= 57" /> </div>
解决方案
问题核心是你给.timedisplay设置了display: inline-flex,这会让容器变成行内级元素,宽度仅包裹内部内容,无法占满父容器(body)宽度,导致margin:auto无法生效。以下两种写法都能实现居中:
写法一:块级flex容器占满宽度,内部元素居中
.timedisplay { display: flex; /* 改为块级flex容器,默认占满父容器宽度 */ justify-content: center; /* 水平方向居中内部元素 */ /* 若需要垂直居中,可添加下面两行,同时给body清除默认边距 */ align-items: center; min-height: 100vh; } body { margin: 0; /* 清除body默认边距,避免垂直居中时出现空隙 */ }
写法二:保持容器宽度包裹内容,容器本身居中
.timedisplay { display: inline-flex; margin: 0 auto; /* 行内级元素通过margin:auto水平居中 */ } body { text-align: center; /* 父容器设置text-align:center,配合inline-flex元素居中 */ }
说明
- 写法一适合需要容器占满页面宽度,内部元素居中的场景;写法二适合容器宽度由内容决定,容器整体在页面居中的场景。
- 两种写法都需要移除原来的
margin-left:40.8%临时样式。
内容的提问来源于stack exchange,提问作者discosteve334
相关产品推荐
相关产品推荐

