What could be causing the unexpected behavior of nth-child?

I'm trying to position an image with the class photo, but unfortunately, the nth-child selector is not having any effect on that particular element. I have searched for various solutions, but none seem to be working!

.container {
  height: 100vh;
  position: relative;
}

.irene {
  position: absolute;
  top: 10%;
  left: 10%;
  width: 60vw;
}

.irene-img {
  position: relative;
}

.irene-img::after {
  content: ' ';
  z-index: -1;
  position: absolute;
  left: 5%;
  top: 5%;
  width: 100%;
  height: 100%;
  border: 5px solid #2ebce2;
}

.irene-title {
  position: absolute;
  left: -10%;
  top: -10%;
  color: rgba(0, 0, 0, 0.4);
  font-size: 10rem;
}

.irene-title span {
  font-size: 5rem;
}

.single__detail__spec {
  position: absolute;
  font-size: 2rem;
  line-height: 2;
  top: 35%;
  right: 10%;
  color: rgba(0, 0, 0, 0.8);
}

.single__detail__spec span {
  font-weight: bold;
}

.single__detail__saying {
  position: absolute;
  width: 400px;
  font-size: 2rem;
  line-height: 2;
  bottom: 5%;
  right: 5%;
  color: rgba(0, 0, 0, 0.8);
}

.photo {
  position: absolute;
  width: 400px;
}

.photo:nth-child(1) {
  left: 0;
  top: 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <base href="https://raw.githack.com/baeharam/Redvelvet-Fansite/master/html/">
  <link rel="stylesheet" href="../css/default.css">
</head>
<body>
  <div class="container">
    <div class="irene">
      <div class="irene-img">
        <img src="../images/about-irene.jpg" alt="">
      </div>
      <p class="irene-title">IRENE <span>배주현</span></p>
    </div>
    <p class="single__detail__spec">
      <span>생일.</span> 1991.03.29<br/>
      <span>별명.</span> 배추, 현이, 엔딩요정<br/>
      <span>취미.</span> 다리미질, 빨래<br/>
      <span>혈액형.</span> A형
    </p>
    <p class="single__detail__saying">
      "lorem ipsum"
    </p>
  </div>
  <img class="photo" src="../images/photo-irene1.jpg" alt="">
</body>
</html>

Does anyone know why the nth-child selector isn't working on the photo class? Any suggestions on how to fix this?

Answer №1

It appears there may be some confusion between the concepts of nth-child and nth-of-type

nth-child(n): This targets an element that is a specified number of siblings after it in the same parent, regardless of their selector match.

nth-of-type(n): This selects an element that is a certain number of matching siblings after it, based on their selectors.

There are 2 solutions to consider for your issue:

  1. img:nth-child(2)
  2. img:nth-of-type(1)

Answer №2

Although the question has already been answered, I would like to contribute a little something: The CSS selector .photo:nth-child(1) is typically written as .photo:first-child.

In this particular case, neither .photo:first-child nor .photo:nth-child(1) will work because the element with the class 'photo' is not the first child of its parent. Both selectors look for the first child element with the class '.photo', so if there are no elements that meet this criteria, the styling won't be applied.

If you are looking to select the first element with the class 'photo', regardless of its position relative to its parent, then you should use the selector .photo:nth-of-type(1).

On the other hand, if you want to target the element based on its positioning relative to its parent, you should use .photo:nth-child(2) since the element with the class 'photo' is the second in line from its parent.

For a comprehensive guide on using :nth-child(n), check out this resource: https://css-tricks.com/useful-nth-child-recipies/

And for an easy-to-understand explanation of :nth-of-type, refer to this guide: https://css-tricks.com/almanac/selectors/n/nth-of-type/. I hope this information proves helpful!

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 Issue of Horizontal Scrolling - None of the elements are out of

I am facing an issue with an unwanted horizontal scroll on my website and I can't seem to identify the cause. The header of my site is quite simple, utilizing display: flex, justify-content: center, marin-top: 5vh, along with some padding on the logo ...

Can CSS3 animations be executed sequentially for each child element?

Have you ever tried creating a CSS3 animation in HTML? You can check out an example here. <div class="parent"> <a href="#">First</a> <a href="#">Second</a> <a href="#">Third</a> </div> With the ...

What is causing the container to overlap with my sidebar-like <nav>?

Why is the fluid-container overlapping in this way, while others are not? Does this look correct to you, or am I overlooking something? It seems incorrect to me. <nav class="nav flex-column float-left"> {links} </nav> <div class="conta ...

Resolved issue with fixed div flickering upon clicking link on Phonegap platform, leveraging Bootstrap

Upon attempting to click a link positioned at the bottom of the screen within a colored div using position:fixed;, I notice that the page momentarily flashes white before displaying the "new" page. Removing the fixed positioning allows the new page to load ...

<h1> </h1> Using attributes in a JavaScript function

Hello, I am trying to figure out how to inherit the h1 style CSS inside a JavaScript function called myFunction. Currently, when the button is clicked, it just displays the default h1 style. Any help would be appreciated. Thank you! <html> <st ...

You are limited to using a maximum of two custom tags within a custom div

I came up with this code that is supposed to style the elements differently based on their tag names. However, when I tested it, the styling did not work as expected. For example, 'London' should be displayed as a large and bold h1 text, while th ...

JQuery mishandles its left positioning

Here's the code snippet I've been working with: $(this).closest("p").after('<strong>' + arMess[iCurIndex] + '</strong>').next().animate({ top: $(this).offset().top - 57, left: -$(this).widt ...

How can I use JavaScript and HTML to print a canvas that is not within the print boundaries?

As someone who is new to javascript, I recently created a canvas function that allows me to successfully print. However, I am encountering an issue with printing large canvas areas. When I navigate to the further regions of the canvas and try to print, i ...

The image slider is blocking the dropdown functionality of the navbar on mobile devices

My code is experiencing a conflict of events. I have created a menu bar using nav bar, as well as an image slider called the caroussel. The issue arises when the window is minimized - the menu bar fails to drop down properly with the presence of the caro ...

Should I use margin-top, padding-top, or top?

I often mix up padding-top, margin-top, and top. My issue arises when I need to create a space of 15px. Using margin-top: 15px seems to work, but I suspect it might be incorrect? .subtitles{ font-size:13px; font-family: "Open Sans","Helvetica Neue", ...

What is the best way to extract the innerHTML of every button and exhibit it in a text box?

How can I create a simpler JavaScript code for clicking buttons to input letters into a text box? Instead of creating getElementByID for each button, is it possible to use some kind of loop? <div id="alpha" > <br/> <div align="cente ...

I am interested in modifying the color of the tick marks on the input[range] element

Seeking Slider Customization Help I am eager to learn how to create and personalize a slider using HTML. Although many resources offer guidance on customizing the slider itself, I have yet to come across any information on customizing the scale. For insta ...

What could be the reason my dropdown menu is not appearing on hover?

Currently, I am in the process of developing a menu using angularJS and google app script within a dialog box. I have been referring to this sample code for guidance. Instead of pasting all my code here, I can summarize what I have come up with: var a ...

Why isn't the image utilizing all the available space?

I'm working on creating a simple card to display services, with just an image and some text. However, I'm facing an issue where the image is not taking up the full width and height of the container as expected. Could someone help me figure out w ...

Placing the date of each blog post at the end of the excerpt

Currently, there is a grid section on the homepage of our site showcasing the two most recent blog posts. I am looking for a Javascript solution to relocate the date to the bottom of each block, outside of the border. For reference, you can visit the follo ...

Update the class name by utilizing template literals

I'm currently in the process of mastering template literals as I have a project where I need to utilize them. However, I seem to be encountering an issue that I can't quite figure out. Here is the code that is currently working: const classes = ...

Achieving a bold border on top of an image without altering the image's dimensions

I'm in need of Photoshop-like selection functionality, but when I add a border to the enclosing div that holds the image, the image ends up smaller by twice the thickness of the border. How can I fix this issue? I have attempted a solution by adding ...

Having trouble resolving this technical problem in Express.js and JavaScript programming

try { console.log('11111') const { data: { tasks }, } = await axios.get('/api/v1/tasks') console.log('22222 ' + await axios.get('/api/v1/tasks') ) console.log('33333 ' + tasks) https://i.sstatic.net/mLLV ...

How to effectively delete the class from a navigation list item

Looking for some inspiration? Check out the basic visuals for this question here. But let me break it down for you. This snippet shows the HTML & CSS behind a tabbed-carousel, with a condensed version for clarity: <style> #myCarousel-100 . ...

The key to highlighting the search terms in bold format

How can I highlight the search terms entered by users in the search box? I want all keywords in every search result to be bolded. For example, when a search term is entered and the results page displays all results with the typed term in bold within each ...