Home > OS >  How apply different media queries rules for a specific div?
How apply different media queries rules for a specific div?

Time:09-02

I'm working on AB Testing variation for a website that use tons of CSS rules and I'm wondering if there is a possibility to apply their classical 767px view media queries for a unique div (something like an iframe behavior)

Indeed, we try to add a second div to give more information and we reduced the size of the original div that used to live with width:100%

I would like to do something like this :

<main>
<section>
  <div >   //Apply CSS like browser is 767px
  </div>
  <div >   //Apply normal CSS
  </div>
</section>

</main>

Perhaps this will help better understanding

Actual Version Variation variation

Massive thanks !!

CodePudding user response:

I think I understand what you have asked. You want to behave a div in tablet media query while at the same time the other div should behave on Media Queries of normal Document size.

You can apply tablet media queries to a specific div and add !important so it will override other media quries that may have applied to its parent div/body element. You can do the same for other div where you want to apply regular media queries.

@media screen and (min-width: 600px) {
  .Original_Div {
    max-width: 80% !important;
    display: inline !important;
  }
  .New_Div{
  max-width: 20% !important;
    display: inline !important;
  }
} 

If I misunderstood your requirements, do let me know so I can provide you with right solution.

CodePudding user response:

You can add any extra styling you like by adding more style blocks to your html. The example below has a media query that will give you the red div only at screen widths of up to 768px. For sizes bigger than that (e.g. a laptop or desktop) then the green div appears. To ensure the div gets no larger than 768px (e.g. a typical tablet size) then use the max-width css rule. If you want to control the height also to make it look like it's a tablet screen then you can use the aspect-ratio css rule (see here for info)

If you're modifying someone else's html then make sure you use a unique class name or id so you control your specific elements. The inspector on the browser's web developer tools (on firefox it's Ctrl Shift I) is useful to find out what's actually being rendered.

body {
  background-color: #282C34;
}
 section {
  display:flex;
  gap: 1rem;
  padding: 1rem;
  height:80vh;
 }

 section > div {
  padding: 1rem 2rem;
 }
 .Original_Div {
  flex-grow:1;
  max-width:767px;
  border: 0.25rem solid red;
  color:red;
 }

 .New_Div {
  flex-grow:1;
  border: 0.25rem solid #00ff00; 
  color: #00ff00;
 }

 @media only screen and (max-width:767px) {
  .New_Div {
    display:none;
  }
 }
  <main>
    <section>
      <div >
        Original with media queries that fit this width
      </div>
      <div >
        New block
      </div>
    </section>
  </main>

  • Related