Ash
Ash

Reputation: 261

CSS internal style is not working, but inline is working. why?

So this is the code. I am not sure what problem there is. So first there is internal and 2nd one below there is inline, which is working. I think the problem is the image because inline css is working fine with other images but not with just one (Capture.png).

<!DOCTYPE html>
<html>
<style>  <!-- this is where I am adding the internal css -->
body{
padding: 0px;
margin: 0px;
}

.cap{                    <!-- this is the class for the image -->
   position: absolute; 
   height:100px; 
   width:200px;
   left:150px; 
}
</style>

<body>
<div class="cap"><img src="Capture.png"/></div>      
</body>
</html>


But this works!

<div class="cap"><img src="Capture.png" style=" position: absolute; 
   height:100px; 
   width:200px;
   left:150px;"/></div>

Upvotes: 1

Views: 3758

Answers (2)

Onel Harrison
Onel Harrison

Reputation: 1334

The code below works because the style is being applied directly to the image.

<div class="cap"><img src="Capture.png" style=" position: absolute; 
   height:100px; 
   width:200px;
   left:150px;"/>
</div>

Notice that the .cap class is for the div that contains the image, not the image itself. The image in the code below isn't working because the CSS you wrote is being applied to the div and not to the image.

<div class="cap"><img src="Capture.png"/></div>

The following piece of code selects the image. You're styles should be applied to the image using the code below.

<style>
.cap img {              <!-- notice the change from ".cap" to ".cap img" -->
       position: absolute; 
       height:100px; 
       width:200px;
       left:150px;
}
</style>

I hope this answers your question. I recommend reading more into CSS Selectors to get a better understanding of how they work. Happy coding!

Upvotes: 1

gavgrif
gavgrif

Reputation: 15489

Your'e not selecting the image with the css because .cap is the div that houses the img - to apply the CSS to the image within that - you will need to target it. Either by applying a class to the image or targetting it within the containing div (using .cap img...). As a rule - it is always best to apply styling in the CSS rather than inline styling.

The reason the inline version worked is because that styling is applied directly to the image.

To use the inline style rule - add img to the .cap as shown below.

.cap img{
   position: absolute; 
   height:100px; 
   width:200px;
   left:150px; 
}

Upvotes: 0

Related Questions