Archived topic
Image in different locations for Mobile vs Desktop
5 replies · Started by Mario on April 20, 2022
Hi,
I want to do the following:
Add an image at the top of the content on mobiles and hide it on desktop
Add the same image on desktop but a little lower than the one on mobiles and hide it on mobiles
I found a way to do it by using hide-on-desktop and hide-on-mobiles classes, but isn't there a better or easier way?
What i dislike the most about this manner is that it might load both images even though its only showing one?
Thanks,
Mario
Hi Mario,
Using the hide-on classes would be the easy and most accurately working way to do this.
If however you want to it not to load totally, you can try adding it through a Block Element, and then utilize the generate_element_display display filter.
Reference: https://docs.generatepress.com/article/generate_element_display/
For instance:
add_filter( 'generate_element_display', function( $display, $element_id ) {
if ( 393346 === $element_id && wp_is_mobile() ) {
$display = false;
}
return $display;
}, 10, 2 );
Kindly replace 393346 with the id of the Element. With this code, the Block Element displays on Desktop and not on mobile. You’ll have to create another Block Element for the other image.
Getting the ID: https://athemes.com/tutorials/wordpress-page-id-and-post-id/
You can compare afterwards if hide-on or the generate_element_display is faster through website speed tests probably if the change is noticeable.
Hope this helps! :)
Hi Fernando,
Sounds like a good alternative to the hide classes option.. Thanks you :)
I am wondering if the following could work as well?
The image i am trying to do this with is the featured image. so what if i enable the featured image option to show on posts (featured images are turned off at the moment cause i manually inserted them) and you provide me CSS to only display the featured images on mobiles.
I could then set the images i manually inserted to only show on desktop with the generate_element_display display filter option.
Would that work?
Thanks,
Mario
Yes, that would work, but to your purpose of have only one image element, you’ll still have two on Desktop, one of them just hidden.
If you want this, you can try this CSS:
@media (min-width: 769px) {
.featured-image {
display:none;
}
}
Hope this clarifies. :)
Thanks Fernando! :)
You’re welcome Mario! Glad to be of assistance! Feel free to reach out anytime you’ll need assistance with anything else. :)