There are many ways to respond to images on web pages. However, all the solutions I have encountered use JavaScript. This made me wonder whether it is feasible to implement image response without JavaScript.
I proposed the following pure CSS solution.
How does it work?
I keep the label within <span>. The src attribute will get the image of the mobile phone version from the server. Then I included a bit of CSS IN THE <span> element.
What ?? Can CSS be embedded in HTML documents?
Yes, as long as you add the scoped attribute, this is very effective in HTML5. In this CSS, I started to use @ media query to add the HD image as the background to <span> from a breakpoint. In the following code, I added only one breakpoint, but you can certainly add a lot as you like.
The background image indicator is used to obtain the image from the server only when necessary. That is to say, it can be obtained only when the media query is satisfied. makes sure that <span> has a correct aspect ratio so that the background image on <span> can be correctly implemented.
Code display
Below are all the code that can be run.
HTML
First, let's look at HTML.
123456 |
< span class = "magik-responsive-image" id = "image-01" > < img src = "http://dummyimage.com/200x150/cdcdcd/000/?text=lo-res" alt = "TODO" > < style scoped> @media screen and (min-width: 701px){#image-01{background-image:url(http://dummyimage.com/1600x1200/dcdcdc/000/?text=hi-res);}} </ style > </ span > |
We also need to modify CSS to hide low-definition images when displaying high-definition images. Tip: Increase backgroud-size: 100%; this allows you to stretch the background while maintaining the aspect ratio unchanged.
1234567891011121314151617 |
.magik-responsive-image { background-repeat : no-repeat ; background- size : 100% ; display : block ; position : relative ; } .magik-responsive-image img { max-width : 100% ; } @media screen and ( min-width : 701px ) { .magik-responsive-image img{ opacity: 0 ; } } |
Benefits
- No JavaScript
- Easy to implement
- It can also be used for video (I will post this content in a later blog article)
Disadvantages
- In a desktop environment, two requests must be sent to the server.
- <Style> the scoped sleep of the label is still not supported in the main browser. It is for this reason that we need to add an id, but adding it to the back-end code is usually not a problem.
Demo
Let's see this demonstration.
Original article address: pure-css-responsive-images-yes-javascript