Issue with the initial element in CSS and the cause remains a mystery

"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:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8dfcfc0dce899989886869c">[email protected]</a>&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. Perhaps someone might have a clue...........................................................................................

Answer №1

The :first-of-type selector targets the first instance of a specific HTML element type, such as div.

In this scenario, because the initial div within the container is classified as .addElement and does not possess the class .elements__newElement, the selector fails to pinpoint any elements.

The functionality of the :first-of-type selector extends solely to the initial HTML element within the parent container that adheres to both the specified type and CSS selector–which, in this case, results in no selection.

To address this issue, it is recommended to relocate the .addElement div from the .elements parent container into its unique container.

Please refer to the demo displayed below.

document.querySelector('.addElement').addEventListener('click', e => {
  const newElement = document.createElement('div')
  newElement.classList.add('elements__newElement')
  newElement.innerText = 'New Element'
  document.querySelector('.elements').appendChild(newElement)
})
.addElementWrapper, .elements {
  width: 70%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  font-family: "Playwrite CO", cursive;  
}

.addElement {
  border: 1px solid black;
  cursor: pointer;
  text-align: center;
  margin-bottom: 25px;
  width: 280px;
}

.elements__newElement {
  display: inline-block;
  margin-top: 10px;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid black;
}

.elements__newElement:first-of-type {
  margin-top: 0 !important;
}
<div class="addElementWrapper">
  <div class="addElement">Add Element</div>
</div>
<div class="elements">
</div>

Answer №2

If none of the .elements__newElement elements are the first of their type on the same layer, your CSS may not work as expected. For example:

<main class="elements">
  <div class="addElement"><p>Add New Entry!</p></div>
  <!-- .elements__newElement:first-of-type does not work since the first div on this layer is the element above -->
  <div class="elements__newElement"><p>New Element 1</p></div>
  <div class="elements__newElement"><p>New Element 2</p></div>
  <div class="elements__newElement"><p>New Element 3</p></div>
</main>

To mimic the behavior of ".first-of-class", you can use the following CSS selector if all .elements__newElement elements are consecutive:

.elements__newElement:not(.elements__newElement + .elements__newElement)

This will select the first .elements__newElement that is not preceded by another .elements__newElement.

In pre-processors like SCSS or LESS, this can be shortened to:

&__newElement {
  display: inline-block;
  margin-top:10px;
  margin-bottom:10px;
  padding: 10px;
  border:1px solid black;
  font-family: "Playwrite CO", cursive;

  &:not(& + &) {
    margin-top: 0;
  }
}

Check out the live demonstration below:

.elements__newElement {
  color: blue;
}

.elements__newElement:not(.elements__newElement + .elements__newElement) {
  color: red;
}
<main class="elements">
    <div class="addElement"><p>Add New Entry!</p></div>
    <div class="elements__newElement"><p>New Element 1</p></div>
    <div class="elements__newElement"><p>New Element 2</p></div>
    <div class="elements__newElement"><p>New Element 3</p></div>
    <div class="elements__newElement"><p>New Element 4</p></div>
</main>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The child element with the specified position within the id element

Is it possible to highlight 'The second paragraph' of p id="dd" using nth-child? I noticed that when I add "#dd" in styles, it stops working properly. <!DOCTYPE html> <html> <head> <style> #dd p:nth-child(3) { back ...

Struggling to align menu items horizontally with CSS? Using the inline property just isn't cutting it

I'm struggling to get my menu to display horizontally, no matter what I try. What am I doing wrong? I think the issue might be with the inline option, but I'm not certain. If someone could help correct my code, I would be very grateful. Thank you ...

IE7 is not applying the conditional CSS styles to content loaded through AJAX

I am currently tackling some challenges with IE7 compatibility in a Rails application that I am developing. It appears that CSS styles implemented from a stylesheet applied with a conditional comment are not being rendered properly when using HAML like thi ...

Spacing for Bootstrap Navbar List Items

I've searched through the CSS and I'm unable to identify what is causing the width between the top level links on my navbar. I need them to be slightly smaller so that when it adjusts for a screen below 900px, it doesn't convert into a 2-row ...

Having trouble with jQuery Animate when trying to change the background-color property?

So, I was experimenting with the jQuery .animate() function and decided to change the background color of a div based on how many pixels the user scrolled. Surprisingly, it didn't work as expected. After switching to the .css() function instead, every ...

`inline-block elements are centered when displayed in Firefox`

I have a question regarding formatting h2 and h3 elements to display as inline-block. Below is the code snippet: <div id="content" class="content-width"> <h2 class="headline"> My Headline </h2> <h3 class="subheadline"> My S ...

Resizing Bootstrap Modal using React with a Personalized Dimension

Is there a way to manually set the width of Bootstrap's Modal React component on my website? I want to be able to define the width in pixels, and if possible, use a const object in the .jsx file for CSS. If not, I can resort to using a .css file. Be ...

Move the accordion slider to the top of the browser

I'm working with an accordion menu that has some long content. To make it more user-friendly, I want to add a slide effect when the accordion items are opened. Right now, if you open the first two menu items, the last item's content is cut off a ...

What is the best way to utilize *ngFor for looping in Angular 6 in order to display three images simultaneously?

I have successfully added 3 images on a single slide. How can I implement *ngFor to dynamically load data? <carousel> <slide> <img src="../../assets/wts1.png" alt="first slide" style="display: inline-blo ...

Enhancing design precision from Figma to flawless pixels

I'm facing the challenge of converting a figma design into an HTML and CSS template with a fixed dimension of 1440px. I'm unsure about where to begin coding in terms of screen size - should I start at 1440px and scale down/up, or begin with mobil ...

Guide on creating a div container that spans the full width of the HTML page with a horizontal scrollbar

I'm facing an issue where the div container is not extending over the entire HTML page with a horizontal scroll bar. Here's a visual representation of my problem: Image Despite using MathJax to display math formulas, the div container does not ...

Switch the text style when hovering, then switch it back upon second hovering

Searching for a method to modify the font of individual letters when hovering over them. The goal is for the letters to revert back to their original font after a second hover (not on the first hover-off). Any assistance would be greatly valued! ...

Can Three.js be used to create a compact canvas?

I've successfully implemented a three.js scene on my website where users can drag to rotate an object. However, I don't want the scene to take up the entire webpage. I tried adjusting the field parameters with the following code: renderer.setSiz ...

Implement a slideshow feature that automatically changes a CSS attribute when preview images are shown

(Apologies for the perplexing title) My intention was to create a slideshow gallery, and I stumbled upon an example here: https://www.w3schools.com/howto/howto_js_slideshow_gallery.asp In this setup, you'll notice previews of images in a small bar b ...

There was an error in calculating the Foundation 5 - 1170 grid

Currently, I am in the process of learning Foundation 5 and working on an app that utilizes a 1170 grid system. The app has 70px columns and 30px gutters (which equals to 1170 when calculated as 70 * 12 + 30 * 11). However, after setting the default values ...

Tips for adjusting the icon size within the <IconContext.Provider> dynamically

Currently, I am using the 'IconContext.Provider' tag to style my icons from the 'react-icons' library. Are there any solutions available to dynamically change the size of the icon based on the size of my media? Is using the global styl ...

Change the classes of the body prior to the initial rendering

I know this may seem like a difficult task, and I understand that what I want to achieve might be nearly impossible. My goal is to incorporate a dark/light mode switch on my website. The challenge lies in the fact that the site consists of static files on ...

Achieving uniform row height in CSS Grid Layout

How do I ensure all footers with a green background have the same height, while also keeping the content height consistent? Current result: https://i.sstatic.net/SrgFq.png Desired output: https://i.sstatic.net/4cr25.png CodePen: https://codepen.io/yas ...

The CSS file cannot be found on the live XAMPP server

Here is the current structure of my project: https://i.sstatic.net/foUiy.png I attempted to link my CSS stylesheet by navigating to the project path, then /css, and finally /style.css. This setup works correctly when opening the .html file locally in a b ...

Implementing a stylish gradient background with HTML 5 progress bar tag

I am trying to customize an HTML5 progress bar tag in a unique way: The background of the bar should have a gradient with a fixed width of 100%, but I want the gradient to only be visible where the value of the bar is... progress[value]::-webkit-progres ...