How can I refactor some repetitive HTML and CSS?
How can I refactor the following repetitive HTML and CSS?
The code is about 10 rooms. The top of Room i is at 40*i pixels.
I used colons to indicate lines th开发者_开发问答at I deleted.
HTML:
<div id="room1">Room 1</div>
<div id="room2">Room 2</div>
:
<div id="room10">Room 10</div>
CSS:
#room1,
#room2,
:
#room10
{
:
top: 40px;
:
}
#room2 {top: 80px}
#room3 {top: 120px}
#room4 {top: 160px}
:
#room10 {top: 400px}
If you require the relative
/absolute
positioning, there is no cleaner way to specify a different top
for n
different div
s.
Sorry, but you just have to write it all out exactly similar to how you have it. After making this myself, I think I have something slightly shorter than yours.
For reference, this is how I'd do it if I needed the positioning:
Live Demo
CSS:
#roomContainer {
position: relative
}
#roomContainer div {
position: absolute;
background: #ccc;
width: 100px;
height: 16px;
padding: 10px;
text-align: center;
outline: 1px solid blue
}
#room1 { top: 0px }
#room2 { top: 40px }
#room3 { top: 80px }
#room99 { top: 9120px }
HTML:
<div id="roomContainer">
<div id="room1">Room 1</div>
<div id="room2">Room 2</div>
<div id="room3">Room 3</div>
</div>
Does this have to be in absolute positioning? Why not do this?
<div id="room1" class="roomHeight">Room 1</div>
<div id="room2" class="roomHeight">Room 2</div>
:
<div id="room10" class="roomHeight">Room 10</div>
.roomHeight {
height: 40px;
}
Each room will still stack as they are naturally under block display, making each one 40px tall will get the same effect as using absolute positioning and declaring the top of each div.
give each the same class and make the class separate each correctly like:
<div id="room1" class="room">Room 1</div>
<div id="room2" class="room">Room 2</div>
:
<div id="room10" class="room">Room 10</div>
the css:
.room {
margin-top: 40px
}
I'm not sure why you used the top property, are they all positioned absolutely?
First I'd suggest to give the "room" div
s also a class for the common css properties: <div id="room1" class="room"></div>
Or if all of them are in a common parent element use that to assign the common css properties:
<div id="allrooms">
<div id="room1">Room 1</div>
<div id="room2">Room 2</div>
</div>
#allrooms div {
...
}
If you don't want that list of css rules for all div
s, it may be worth considering applying the left
properties directly to the div
s: <div style="left: 20px">Room 1</div>
it might be better to use a div to wrap the entire row instead then...so you have a
<div class="schedulerRow">
<div id="room1" class="room">room 1</div>
<div id="scheduler1">Enter Time division elements in here</div>
</div>
Css
.schedulerRow, room { height: 40px;}
then you can interact with the time division elements on the same row without affecting the other room rows.
精彩评论