Search code examples
htmlcssposition

Position right div over the left in mobile view


Is it possible to stack right side div over the left sided div in mobile view with the help of CSS? The default behavior is the right sided div floats under the left sided div.

CSS:

.left {
    position: relative;
    float: left;
    background: #F48024;
    width:576px;
    height: 324px;
}
.right {
    position: relative;
    float: left;
    background: #EFF0F1;
    width:576px;
    height: 324px;
}

HTML:

<div class="main">
    <div class="left"></div>
    <div class="right"></div>
</div>

Trying to achieve 3rd layout of this diagram.

enter image description here


Solution

  • You can achieve this by using flex box! Change Your css to this:

    .main{
        display:flex;
        flex-wrap:wrap;
        justify-content: center;
    }
    
    .left {
        position: relative;
        background: #F48024;
        width:576px;
        height: 324px;
    }
    
    .right {
        position: relative;
        background: #EFF0F1;
        width:576px;
        height: 324px;
    }
    
    @media screen and (min-width:1152px){
      .main {
          justify-content: space-between;
      }
    
      .left {
          order:2;
      }
    
      .right {
          order:1;
      }
    }
    

    order property determines which element stacks first. You can read more about flex box here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/