Search code examples
cssshow-hide

Show a div on desktop and show another div on mobile with CSS


I want to show a particular div on desktop and tablet but I wanna hide this div in the mobile screen. In the mobile screen I wanna show another div, so I want to swap the two divs.

This is my attempt:

.div-only-mobile {
    visibility: hidden;
    display: none;
}

@media screen and (max-width: 849px) {

.div-no-mobile {
    visibility: hidden;
}

.div-only-mobile {
    visibility: visible;
    display: block;
}

}

Solution

  • Yes using media query you can hide div at certain screen-resolution as in below example, but CSS styling property visibility just hides an element, but still layout is visible that effects other elements, to hide it totally use display as none, try below example,

    .desk{
      width:400px;
      height:200px;
      background:red;
    }
    .div-only-mobile{
      width:400px;
      height:200px;
      background:orange;
    }
    @media screen and (max-width : 1920px){
      .div-only-mobile{
      visibility:hidden;
      }
    }
    @media screen and (max-width : 906px){
     .desk{
      visibility:hidden;
      }
     .div-only-mobile{
      visibility:visible;
      }
    }
    <div class="desk">Large Screen</div>
    <div class="div-only-mobile">Only Mobile</div>
    <p>Demo Text.</p>