Reputation: 91
I want to know if it is possible for my front page to load an image dedicated for mobile users only. I know it is possible with javascript, but I want to know if I can achieve the same using CSS only. I have tried to do some research but can't find what I am looking for. I do not mean resizing the image based on the screen size, but loading a mobile-friendly image.
Upvotes: 7
Views: 7259
Reputation: 4202
Based on your comment to @NullDev, you will need to create a div at the appropriate size and apply the image as a background image on an element in order to condition what is loaded via CSS.
For example:
HTML:
<div id="image"></div>
CSS:
#image {
position: relative;
width: 400px;
height: 400px;
background-image:url('/path/to/image');
background-size: cover;
background-repeat: no-repeat;
}
Then apply the media query:
@media only screen and (max-width : 480px) {
#image{
background-image:url('/path/to/mobile/image');
}
}
I hope this helps.
Upvotes: 1
Reputation: 7303
Yes this is possible. You can use Media Querys. Example CSS:
#yourimage {
display: none;
}
@media (max-width: 500px) {
#yourimage {
display: block;
}
}
This code is for html images tho. Here is a JSFiddle:
https://jsfiddle.net/vqfLokpa/
Just hit run and then start to make your browser window smaller.
Upvotes: 2
Reputation: 8795
Make use of media query
to change background-image
at different screen resolutions
as below,
div{
width:100%;
height:400px;
background:url('http://placehold.it/350x150/f22/fff');
background-size:100% 100%;
}
@media screen and (max-width : 480px){
div{
background:url('http://placehold.it/480x150/f12/fff');
background-size:100% 100%;
}
}
@media screen and (max-width : 320px){
div{
background:url('http://placehold.it/320x150/e12/fff');
background-size:100% 100%;
}
}
<div></div>
Check this jsFiddle.
Upvotes: 6
Reputation: 703
You can use media queries to apply classes depending on the screen size.
#img {
display: none;
}
/* Large Devices, Wide Screens */
@media only screen and (max-width : 1200px) {
}
/* Medium Devices, Desktops */
@media only screen and (max-width : 992px) {
}
/* Small Devices, Tablets */
@media only screen and (max-width : 768px) {
}
/* Extra Small Devices, Phones */
@media only screen and (max-width : 480px) {
#img{
display: block;
}
}
/* Custom, iPhone Retina */
@media only screen and (max-width : 320px) {
}
Upvotes: 2