【问题标题】:Good practice with css class and id [closed]css 类和 id 的良好实践 [关闭]
【发布时间】:2020-03-07 15:18:06
【问题描述】:
我想知道使用 css 的干净代码实践。假设我有类似的东西:
#island1 {
position: relative;
margin-top: 5vh;
margin-left: 55vw;
width: 20vw;
height: 20vw;
border-radius: 50%;
background: #222222;
box-shadow: -17px -17px 34px #171717,
17px 17px 34px #2d2d2d;
}
我想要其中的 6 个,但大小和边距不同。在不为每个元素重复相同代码的情况下,最好的方法是什么?
【问题讨论】:
标签:
css
coding-style
code-cleanup
【解决方案1】:
您可以使用 CSS 类:
.island {
position: relative;
margin-top: 5vh;
margin-left: 55vw;
width: 20vw;
height: 20vw;
border-radius: 50%;
background: #222222;
box-shadow: -17px -17px 34px #171717,
17px 17px 34px #2d2d2d;
}
.island1 {
width: 10vw;
height: 10vw;
margin-top: 5vh;
margin-left: 15vh;
}
.island2 {
width: 30vw;
height: 30vw;
margin-top: 15vh;
margin-left: 25vh;
}
...
.island6 {
width: 60vw;
height: 60vw;
margin-top: 35vh;
margin-left: 45vh;
}
HTML:
<div id="island1" class="island island1"></div>
<div id="island2" class="island island2"></div>
...
<div id="island6" class="island island6"></div>
【解决方案2】:
你可以创建一个属性不变的类
.islands {
position: relative;
border-radius: 50%;
background: #222222;
box-shadow: -17px -17px 34px #171717,
17px 17px 34px #2d2d2d;
}
对于所有岛屿,指定其他类或 id 的大小和边距
#island1{
margin-top: 5vh;
margin-left: 55vw;
width: 20vw;
height: 20vw;
}
#island2{
margin-top: 1vh;
margin-left: 1vw;
width: 10vw;
height: 10vw;
}