Utilizing CSS selectors to pinpoint specific elements on a webpage

As I continue to enhance my CSS skills, I stumbled upon a challenging puzzle that requires me to figure out how to select each individual image on a webpage using selectors. Here is the provided HTML code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <style>
    @keyframes spin{
      from{transform:rotate(0deg)}
      to{transform:rotate(360deg)}
    }

    /*CSS Selector goes here*/{
      animation-name: spin;
      animation-duration:1000ms;
      animation-iteration-count:infinite;
    }
  </style>
  <body>
    <header>My Tutorial 3</header>
    <img src="H:\ASECOND YEAR\Web Tutorial 3\harley.jpg" />

    <article>
      <header>About this tutorial</header>
      In this tutorial I need to make a picture spin for ever...
      <img src="H:\ASECOND YEAR\Web Tutorial 3\hellcat.jpg" />
    </article>

    <footer>my footer
      <img src="H:\ASECOND YEAR\Web Tutorial 3\smiley.jpg" /></footer>   
  </body>
</html>

After some trial and error, I discovered that I can target the image within the article by using article img, however, I struggled to select the other images. I attempted to use header~img in hopes of selecting the first image based on its preceding header tag, but it ended up spinning both the first and second image. Likewise, using img:nth-of-type(2) did not select the last image as I anticipated (index starting at 0). Can someone provide guidance on the correct selectors to use in order to isolate each image individually? Selectors can indeed be quite tricky to master.

Furthermore, I managed to identify a way to target the last image by utilizing footer img, although using img:last-child unexpectedly affected the middle and last images with the spinning animation.

Answer №1

Let's start by examining the selectors you attempted that did not meet your expectations:

  • header ~ img - The ~ selector is known as the general sibling selector and it picks all img tags that have header as a previous sibling. Both the first and second images have a header element before them under the same parent, so both are selected.

  • img:nth-of-type(2) - The nth-* selectors only work among elements sharing the same parent. The second and third img tags are within different parents (article and footer respectively). As a result, since the parent of the first img has only one element, it doesn't match the nth-of-type(2) selector.

  • img:last-child - The last-child selector picks the img that is the last child in every parent. The first img is not the last child under its parent (body) because there are more elements following it, hence it is not selected. The second and third img tags are indeed the last child elements under the article and footer respectively, so they are selected.

Now, if you want to select each individual image, there are different ways to do so. Here's how you can achieve it based on your current markup:

  • The first img can be selected with body > header + img.
  • The second img can be selected with article > header + img or article img.
  • The third img can be selected with footer > img or footer img.

The important part of the first two selectors is what comes before the header + img as it narrows down the selection. The first selector picks only img elements following a header with body as their parent. Similarly, the second selector picks only img tags following a header with article as their common parent.

In the code snippet below, these selectors are used to apply different colored borders to each img element, demonstrating how they function:

body > header + img {
  border: 2px solid red;
}
article > header + img {
  border: 2px solid green;
}
footer > img {
  border: 2px solid blue;
}
<header>My Tutorial 3</header>
<img src="http://lorempixel.com/100/100/nature/1" />

<article>
  <header>About this tutorial</header>
  In this tutorial I need to make a picture spin for ever...
  <img src="http://lorempixel.com/100/100/nature/2" />
</article>

<footer>my footer
  <img src="http://lorempixel.com/100/100/nature/3" />
</footer>

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

What is the best way to position my inline-flex element at the bottom of the page?

I'm trying to understand how flex-inline works. I want to make the height expand to 100% and reach the bottom of the screen without overcrowding it with content. html,body{margin:0;padding:0} body{background:black;} #sidebar{ display: inline-f ...

My div won't stay fixed in the layout no matter what I try

Being fairly new to css, divs, and everything in between, I decided to create a simple layout for my band without unnecessary links like bio or merch store. Instead, I wanted separate spaces for our video, music player, and a Facebook window. I successful ...

Effect of Active or Focus on the HTML <ul> element

Check out this example of a UL tag: <ul style="list-style-type:none; padding:5px ; border:solid 1px #666666;"> <li>I am waiting </li> <li>I am waiting </li> <li>I am waiting </li> <li>I am wa ...

Tips for customizing the appearance of a disabled checkbox

I'm curious if you have any ideas on how to customize the appearance of a disabled checkbox? For example: <input type="checkbox" value="All Terrain Vehicle" name="exfilter_All Terrain Vehicle" id="exfilter_All_Terrain_Vehicle" ...

What strategies can be implemented to avoid using .stop() in specific scenarios?

Currently, I am working on a jQuery animation where clicking on a tile should display its information by hiding all other tiles and showing its details. While I have implemented .stop() to prevent queuing issues, I encountered a problem with the transition ...

How come my image is not aligned to the right of the header in my HTML code?

My attempt to align an image to the right side of my heading using code was unsuccessful. Here is the HTML snippet I used: /* Aligning with CSS */ #colorlib-logo img { display: flex; align-items: center; width: 30px; height: 30px; } #colorli ...

How can I make an element stick at the bottom of another element using the top position

I have two stacking elements of varying heights within a scrolling container. When the lower element extends below the bottom of the container, I want to display a part of it affixed to the bottom. To achieve this, I applied position: sticky to position ...

What is the best way to make a div expand to the full width of the screen while still being contained within its parent div?

I am facing an issue with the black bar at the bottom of the slider not stretching full-width on the screen. While it works fine on the left, the right side is cut off at the container edge. I am using Master Slider if that's relevant information. Can ...

The outline none property on the Material UI IconButton is malfunctioning

https://i.sstatic.net/S5zWD.png Attempting to style with CSS as shown in the following example: <CustomColorIconButton> <DeleteForeverIcon /> </CustomColorIconButton> const CustomColorIconButton = withStyles({ root: { c ...

What is the best way to conceal text while retaining icons on a compact screen?

How can I hide the text links for Home, Reservations, My Reservations, About, and Settings on smaller screens while still keeping the icons visible? Currently, I am using the following resources: http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.1 ...

Tips for adjusting the font size on the Google Maps mapType controller

Is it possible to adjust the font size of a Google Maps mapType controller using HTML or CSS? I've managed to change the size of the controller, but struggling with the font size. https://i.sstatic.net/1n9oU.png HTML: <div #map id="map" style=" ...

Turn off smooth scrolling in Bootstrap 5 using HTML and CSS techniques

On my website, I have implemented anchor links that activate smooth scrolling when clicked, thanks to the Bootstrap feature. However, the unique layout of my website requires me to turn off smooth scrolling in either the HTML or CSS code. I appreciate an ...

Scrolling to an element is not possible when it has both position absolute and overflow-x hidden properties

My issue involves animating ng-view with a slideup animation, requiring absolute positioning of elements and overflow-x: hidden to clip the content. However, I need to use the scrollTo element functionality on one sub-page, which doesn't work when bot ...

Caution: The presence of <li> within another <li> is not permitted in validateDOMNesting()

I am facing a challenging background error warning that I am struggling to solve. As a beginner, I understand the need to change li, but I'm not sure where to begin. Can someone please assist me with this error warning: next-dev.js?3515:20 Warning: va ...

Bootstrap carousel powered by AngularJS

Struggling to incorporate bootstrap, angular, and a carousel to showcase images from local folders on my drive. Unsure how to customize the angular file properly. The example provided in the link below fetches images from the Internet, but I need to modify ...

Adding multiple styles using ngStyle is currently not possible

When using ngStyle to add height and width styles to an img element, I encountered a strange issue: <img class="image-full-view" [ngStyle]="{'height': selectedImage.heightSize, 'width': selectedImage.widthSize}" [src]="selectedImage ...

Having issues with image hover and click functionality

My website has an image with the cursor set to pointer and a function that should show a hidden element when clicked. However, it's not working at all. When I hover over it or click on it, nothing happens. Here is a screenshot of the issue along with ...

In the realm of typesetting, a punctuated line gracefully weaves its way between two

I am trying to create two sentences with a fixed width of 30%, but the first words in my div go to the next line. The class="left" words are not displaying properly, and then my second div "words" gets mixed with the first div. HTML <div class="bg"> ...

disable the button border on native-base

I'm attempting to enclose an icon within a button, like so: <Button style={styles.radioButton} onPress={() => { console.log('hdjwk'); }}> <Icon ...

Stepper wizard experiences a variation in CSS styling when minified

Two plunkers showcasing material design wizard selectors are causing different behavior upon stepper clicks. One uses a minified version of CSS while the other is expanded. The issue arises with the transition effects in the .step-wizard .progressbar class ...