I'm here with a problem that I don't see how I can solve it.
I have a header "topo" with a image.
And I want that image in my desktop and tablet versions, but in my media query for smartphone with 480px I want to show other image, a smaller image.
So in my 480px media query, I'm trying to give background-image with CSS and make my #logo image as display:none
, so I can have my smaller image for smartphone.
But it's not working, can somebody there give me a little help?
This is my html for this issue:
<header id="topo">
<span id="logo">
<a href="index.php"><img src="../images/logo.png" /></a>
</span>
</header>
I have this media query for mobile
@media screen and (max-width:480px)
{
*
{
margin:0;
padding:0;
border:0;
outline:none;
}
body
{
min-width:320px;
}
#topo
{
width:226px;
margin:10px auto 0 auto;
background:url(../imagens/logo%20-%20C%C3%B3pia.png);
}
.....
}
This is my media query for tablet:
@media screen and (min-width:481px) and (max-width:768px)
{
*
{
margin:0;
padding:0;
border:0;
outline:none;
}
#topo
{
width:700px;
margin:10px auto 0 auto;
background:yellow;
}
#logo
{
float:left;
}
....
}
In this instance, when you set display:none
on the img
element, the a
element collapses upon itself because the img
element is the a
element's only child. The background image is therefore not displayed because the a
element has a height of 0
. To solve this, you should set a height on the a
element and change the element's display
from inline
to block
.
@media screen and (max-width:480px) {
#topo {
width:226px;
margin:10px auto 0 auto;
background:url('//placehold.it/200/0ff');
}
#topo a {
height:200px;
display:block;
}
#topo img {
display:none;
}
}
The above solution may work for a majority of scenarios, however, if you want to avoid setting a height on the element, i'd suggest doing something like this instead:
Add both img
elements into the markup, giving each mutually exclusive classes.
<a href="index.php">
<img class="hidden_mobile" src="//placehold.it/200/000" />
<img class="hidden_desktop" src="//placehold.it/200/f00" />
</a>
Use something along these lines and hide the respective image based on the screen size. The benefit to this approach is that you can reuse those classes for other scenarios. In addition, you can avoid having to set a height on the a
element.
@media screen and (min-width:481px) {
.hidden_desktop {
display:none;
}
}
@media screen and (max-width:480px) {
.hidden_mobile {
display:none;
}
}