Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add CSS class to the HTML5 picture element

Tags:

html

css

The code below uses the picture HTML5 element to display a different versions of an image, depending if the user uses a mobile device or a desktop.

Question: How can I make only mobile_image.png 10% the width of the viewport (window)? Why can't I add a css class or style tag to source media?

<div class="my_container">
<a href="#back_to_top">
<picture>
<source media="(max-width:767px)" srcset="mobile_image.png">
<source media="(min-width:768px)" srcset="desktop_image.png">
<img src="fallback_image.png" alt="Back to Top">
</picture>
</a>
</div>

Using the code below - nothing!

@media only screen and (max-width : 767px) {
.my_container {
width:10%;
height:auto;
}
}
like image 901
Malasorte Avatar asked Jan 18 '15 08:01

Malasorte


People also ask

Can you add a class to an image CSS?

For the CSS, you will need the image class names. There are default class names, which you can use to style all images at once, or you can add your own custom class names. With your own custom class names, you can style an individual image or multiple images of your choice.

Can I use class in IMG tag?

Classes (i.e. classnames) are used for styling the img element. Multiple classnames are separated by a space. JavaScript uses classes to access elements by classname. Tip: class is a global attribute that can be applied to any HTML element.

Can we add class in CSS?

Yes you can - first capture the event using onmouseover , then set the class name using Element. className . If you like to add or remove classes - use the more convenient Element.

Do you add images to HTML or CSS?

Summing up: if an image has meaning, in terms of your content, you should use an HTML image. If an image is purely decoration, you should use CSS background images.


1 Answers

You can also add classes to the "img src" line of the code:

<picture>
   <source media="(min-width:768px)" srcset="tablet_image.png">
   <source media="(min-width:992px)" srcset="desktop_image.png">
   <img src="fallback-mobile_image.png" alt="whatever" class="img-responsive center-block etc">
</picture>

The classes are then applied to whichever image is being rendered by the screen size. Definitely helpful for when you're using a framework like Bootstrap or Foundation.

like image 102
reidb Avatar answered Sep 23 '22 13:09

reidb