mikejoelbuchanan
mikejoelbuchanan

Reputation: 11

How to access an element within an element in css?

In the following code, how would I address the 'img' element in CSS? I'm having a hard time getting it to work.

<div id="random1">
<div id="random2">
<div id="random3">
<img src="images/image.jpg">
</div>
</div>
</div>

Upvotes: 0

Views: 1904

Answers (4)

Spanka
Spanka

Reputation: 180

To expand on some theory here... The more specific a selector is, the more priority it takes. There's more to it than that, but that's the general gist.

Spaces between selectors basically say "child @ any depth" whereas a greater than symbol (>) states "immediate child only". Immediate child selectors are more specific than any-depth selectors.

Any of these could style the image in your example:

#random1 #random2 #random3 img { blah }
#random1 img { blah }
#random2 img { blah }
#random3 img { blah }

So could this (because img is an immediate child of #random3):

#random3 > img { blah }

But this would fail, because the img is not immediately inside random2, it's inside random3 inside random2:

#random2 > img { blah }

So you could start off lazy with #random1 img. If that failed to stick, #random3 > img as suggested. If that happened to fail as well, just get more and more specific. As an example, where each line gets more and more specific

#random3 > img {}
#random2 > #random3 img {}
#random1 > #random2 > #random3 > img {}

And if that last one didn't work, you really need to look at some weirdo CSS because 3 immediate child selectors is kinda crazy talk.

Upvotes: 1

durbnpoisn
durbnpoisn

Reputation: 4669

You should just be able to nest the listings:

#random1 {
//stuff
}

#random3 img{
//other stuff for the image
}

And so on. This will localize the img sepecifically for random3, and not affect other img tags.

Upvotes: 0

TylerH
TylerH

Reputation: 21085

There are several ways to do this. If this is the extent of your markup (HTML), you can use element selectors (img and div are examples of elements) in CSS:

img {
    width: 500px;
}

If your markup will expand at a later date, you can use Classes (for multiple instances) or IDs (for unique instances). I'll show you classes and then IDs.

HTML:

<img class="myImg" src="images/image.jpg">

CSS:

.myImg {
    width: 500px;
}

Or for IDs, HTML:

<img ID="myImg" src="images/image.jpg">

CSS:

#myImg {
    width: 500px;
}

If you want to select the img as a child of the div #random3, you can use a direct descendant selector:

#random3 > img {
    width: 500px;
}

Upvotes: 1

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

Use > immediate descendant selector like this:

#random3 > img{
  /* Css Rules */
}

Upvotes: 2

Related Questions