首页 > 解决方案 > 如何优化此 css 代码,以免在 html 中多次编写相同的 css 代码?

问题描述

我有一个输入框。这些值已经在其中定义或将在其他一些规则中生成,这就是为什么它们都有单独 的 id 的原因。

html代码:

<input class="box" type="text" style="width:8%; text-align:center" id="a" value="A" readonly="true"/>
<input class="box" type="text" style="width:8%; text-align:center" id="b" value="B" readonly="true"/>
<input class="box" type="text" style="width:8%; text-align:center" id="c" value="C" readonly="true"/>
<input class="box" type="text" style="width:8%; text-align:center" id="d" value="D" readonly="true"/>
<input class="box" type="text" style="width:8%; text-align:center" id="e" value="E" readonly="true"/>

现在假设,我必须将宽度8减小到 6。然后我必须写width:6%'5 次,这是多余的,因此我不想使用它。有什么办法可以改进或为此编写任何循环吗?

标签: javascripthtmlcss

解决方案


您的 HTML 元素已经具有 CSS 类属性,因此您可以像这样设置它们的样式:

.box {
  width: 6%;
  text-align:center;
}
<input class="box" type="text" id="a" value="A" readonly="true"/>
<input class="box" type="text" id="b" value="B" readonly="true"/>
<input class="box" type="text" id="c" value="C" readonly="true"/>
<input class="box" type="text" id="d" value="D" readonly="true"/>
<input class="box" type="text" id="e" value="E" readonly="true"/>


推荐阅读