我刚开始用更少的方法工作,我正努力在一些简单的盒子上工作,以获得更好的理解。有4盒有不同的颜色和大小,但在div:nth-子(2),它总是创建两个盒子。我怎么才能把它修理成一个盒子呢?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Preprocessors</title>
<link rel="stylesheet" href="less/style.css">
</head>
<body>
<nav>Navigation Bar</nav>
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<footer>Footer</footer>
</body>
</html>
*{
margin: 0;
}
html{
background-color: @mainColor;
}
.container {
min-height: 50vh;
display: flex;
align-items: center;
justify-content: space-between;
}
div:nth-child(1){
.boxes(@box1Color, 100px)
}
div:nth-child(2){
.boxes(@box2Color, 200px)
}
div:nth-child(3){
.boxes(@box3Color, 250px)
}
div:nth-child(4){
.boxes(@box4Color, 50px)
}
有了容器,没有第二个第n个子文件,页面看起来很好,但是当添加第二个盒子时,所有的东西都会凝结,一个大的盒子就在常规的盒子后面。
.boxes(@color, @wh){
border-radius: 8px;
border: solid black 2px;
background-color: @color;
height: @wh;
width: @wh;
}
发布于 2022-01-31 16:57:52
而不是这个选择器。
div:nth-child(2){
.boxes(@box2Color, 200px)
}
...you应该更具体,因为这将适用于所有的DIVs,它们是其他任何东西的第二个子级。
使用组合选择器中父容器的类将选择限制为该容器的子容器,如下所示:
div.container > div:nth-child(2){
.boxes(@box2Color, 200px)
}
其他孩子也一样。
在“更少”中,您还可以将它(以及其他子选择器规则)写为
div.container {
&>div:nth-child(1){
.boxes(@box1Color, 100px)
}
&>div:nth-child(2){
.boxes(@box2Color, 200px)
}
&>div:nth-child(3){
.boxes(@box3Color, 250px)
}
&>div:nth-child(4){
.boxes(@box4Color, 50px)
}
}
P.S.:实际上,代码中的主要错误是在设置后直接关闭.container
规则,而不是将结束括号(}
)移到子div规则之后。
通过使用直接子选择器>
和子规则中的父占位符的&
占位符,我上面的较少代码也更加具体。
https://stackoverflow.com/questions/70929651
复制相似问题