Una Koala
Una Koala

Reputation: 169

How can I optimise this css code for not writing same css code several times in html?

I have an input box. Where the values are already defined in or it will be generated in some other rules that's why they all have individual id's.

html code:

<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"/>

now suppose, i've to decrease the size of the width 8 to 6. Then I've to write width:6%' 5 times, which is redundant thus I don't wanna use it. Is there any way I can improve this or write any loop for this?

Upvotes: 0

Views: 40

Answers (2)

Wes
Wes

Reputation: 1090

The whole point of CSS classes is exactly to handle this situation. Rather than put style="width:8%; text-align:center" in each tag, you could use your box class to change all of them at once.

INPUT.box {
  width: 8%;
  text-align: center;
}

The trick, of course, is to use the right CSS selector to access the things you want to change as a group. INPUT.box means "all INPUT elements with the class box"

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors

Upvotes: 0

ROOT
ROOT

Reputation: 11622

Your HTML elements already have a CSS class attribute, so you can style them like this:

.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"/>

Upvotes: 3

Related Questions