"first of type" dont like to work:
.elements {
width:70%;
margin:0 auto;
display:flex;
flex-direction: column;
.addElement {
width:280px;
text-align: center;
border:1px solid black;
font-family: "Playwrite CO", cursive;
margin-bottom: 25px;
&:hover {
cursor: pointer;
}
}
&__newElement {
display: inline-block;
margin-top:10px;
margin-bottom:10px;
padding: 10px;
border:1px solid black;
font-family: "Playwrite CO", cursive;
&:first-of-type {
margin-top: 0 !important;
}
}
}
HTML:
<!DOCTYPE html>
<html lang="DE">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Link Tree Clone</title>
<link rel="stylesheet" href="css/style.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Playwrite+CO:[email protected]&display=swap" rel="stylesheet">
</head>
<body>
<main class="elements">
<div class="addElement"><p>Neuen Eintrag hinzufügen!</p></div>
</main>
<script src="javascript/main.js"></script>
</body>
</html>
i try to set the margin-top, of the first element which has the class"elements__newElement" to 0.
Nobody knows the answer……………………………………………………………………………….
2
Answers
Your CSS won’t work if none of the
.elements__newElement
is the first of type of the same tag on the same layer. Such asWhat you could do is to use something like to mimic "
.first-of-class
" behavior, if all the.elements__newElement
are consecutive:It means select
.elements__newElement
that is not preceded by another.elements__newElement
, which will only select the first.elements__newElement
.With pre-processors like SCSS or LESS, it could be shortened like:
Here’s a live demo:
The
:first-of-type
selector works on the first occurrence of the type of the HTML element, in this case:div
.Because the first
div
in the container is actually the.addElement
div
, but thisdiv
doesnt have the class.elements__newElement
, the selector doesn’t actually select anything.The
first-of-type
selector is only applied to the first html element in the parent container that matches the type and matches the css selector, in your case, nothing.A solution is to move the
.addElement
div out of the.elements
parent container and into it’s own container.See the demo below.