Question3r
Question3r

Reputation: 3822

Reorder DOM elements on different screen sizes

I want to create a component with a text on the left or right side and an image next to it.

enter image description here

Currently I just use a bool parameter to check which element comes first. On larger screen sizes everything is fine but when it comes to smaller ones every image should be above the text.

If the text is on the left side this doesn't work because it places itself above the image.

I created an working example showing the problem

https://codesandbox.io/s/3qpj23y3o1

How can I fix this behaviour? Maybe there is a way getting rid of this if statement too? Because the only thing that differs is the order of the image and the text container.

Upvotes: 3

Views: 158

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Since you're working with CSS grid you could do it simply by using grid-template-areas and create your areas img and txt :

   .textImageSectionContainer {
      ...
      grid-template-areas:'img' 'txt';

    }
    .imgContainer {
       ....
       grid-area:img;
      }
     .txtContainer {
       padding: 50px;
       grid-area:txt;
      }

you could apply the above rules for small sizes only, in this codesandbox example i set the above rules for screen size under 700px

Update:

You could use class binding to avoid the if statement and redundant code :

<template>
  <div
    :class="{ imgleft: imageLeft, imgright: !imageLeft }"
    class="textImageSectionContainer"
  >
    <div class="imgContainer"><img :src="imgUrl" class="img" /></div>
    <div class="txtContainer">
      <div class="headerText">{{ headerText }}</div>
      <div class="mainText">{{ mainText }}</div>
    </div>
  </div>
</template>

and CSS rules should be like :

.imgleft {
  display: flex;
}

.imgright {
  display: flex;
  flex-direction: row-reverse;
}

Upvotes: 3

Related Questions