Search code examples
htmlcssresponsive-designlesssocialshare

Applying a class based on media query - pure CSS or HTML needed


I need a media query (or similar) using pure CSS, HTML or possibly LESS (as long althogh pre-compiled won't work) to apply a particular class to an ID depending on the screen height. I'm setting classes defined by Add2Any - not css properties.

jsfiddle

What I want to do is set the div #add2any to this for small screens.

  <div id="add2any" class="a2a_kit a2a_default_style">

Otherwise I want this:

  <div id="add2any" class="a2a_kit a2a_kit_size_32 a2a_default_style">

Is this possible, and how?

Looking for a non-javascript/not Jquery solution to avoid time lag and having a <div> for each style and showing only the relevant one.

Background

The idea is to change the layout and size of the AddToAny bar for small screens, so instead of 32px images it displays a totally different style of compact bar, with less buttons, and using AddToAny's classes means future changes they make would not be dependent on fixed css in my stylesheets. Browser compatibility is important.

CSS so far

@media screen and (max-height: 430px) {
  .a2a_button_google_plus, .a2a_button_pinterest, .a2a_button_print { display:none;}
  #add2any a, hr#add2any, hr#add2any a, .a2a_divider { font-size: 15px; padding-top:2px; padding-bottom:-2px; }
  .a2a_divider { top:5px ; position: relative}
}

Edit

Unable to find solution from any of these, I'm using foundation framework.

conditional CSS based upon div not screen

Toggle mobile view in Foundation using CSS class or JS

How to toggle class using pure javascript in html

**Edit 2 **

Suggestions of using Less or Sass from this question seem like overkill, since the solution would be needed on every page.

Self-hosting the script and adding some javacript to it might be a better choice, the class names look certain to remain the same even if the script changes since all Customize instructions encourage direct use of AddToAny's class names.


Solution

  • Edited

    If you have this html:

     <div  class="a2a_kit a2a_default_style">
     <div  class="a2a_kit a2a_kit_size_32 a2a_default_style">
    

    You can make a media query like this:

     /* first state */
     .a2a_kit { display: block; }
     .a2a_kit.a2a_kit_size_32 { display: none; }
    
     @media screen and (max-height: 430px) {
         /* reverse behaviour on max-height 430 px */
         .a2a_kit { display: none; }
         .a2a_kit.a2a_kit_size_32 { display: block; }
     }