如何重构一些重复的 HTML 和 CSS?
如何重构以下重复的 HTML 和 CSS?
代码大约是10个房间。房间 i 的顶部位于 40*i 像素处。
我使用冒号来表示我删除的行。
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}
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 that 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}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您需要
相对
/绝对
定位,则没有更简洁的方法来为n
不同的top
指定不同的top
div
。抱歉,您只需
完全写出所有内容,就像您的方式一样。我自己做了这个之后,我想我的东西比你的稍微短一些。作为参考,如果我需要定位,我会这样做:
现场演示< /em>
CSS:
HTML:
If you require the
relative
/absolute
positioning, there is no cleaner way to specify a differenttop
forn
differentdiv
s.Sorry, but you just have to write it all out
exactlysimilar 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:
HTML:
这必须是绝对定位吗?为什么不这样做呢?
每个房间仍然会堆叠,因为它们自然地在块显示下,使每个房间高 40 像素将获得与使用绝对定位并声明每个 div 顶部相同的效果。
Does this have to be in absolute positioning? Why not do this?
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.
给每个相同的类并使类正确地分开每个类,例如:
css:
我不确定为什么你使用 top 属性,它们都是绝对定位的吗?
give each the same class and make the class separate each correctly like:
the css:
I'm not sure why you used the top property, are they all positioned absolutely?
首先,我建议为“房间”
div
提供一个通用 css 属性的类:或者,如果它们都在一个公共父元素中,请使用它来分配公共 css 属性:
如果您不希望所有
div
都有该 css 规则列表,那么它可能值得考虑将left
属性直接应用于div
:< /代码>
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:If you don't want that list of css rules for all
div
s, it may be worth considering applying theleft
properties directly to thediv
s:<div style="left: 20px">Room 1</div>
最好使用 div 来包装整行,然后...所以你有一个
<代码>
CSS
.schedulerRow, room { height: 40px;}
那么你就可以与同一行的时分元素进行交互,而不会影响其他房间行。
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.