Change the same css class property through javascript

82 views Asked by At

I have a same class in multiple pages. And I have a control on css though which I can change the property of the css.

div.single-column div.middle {
    padding: 10px 20px;
    clear: both;
    position: relative;
    top: 70px;
} 

In one page I want to make top:70px and rest of the pages I want it top:0

Is there any way I can control this through JavaScript on one page?

4

There are 4 answers

1
Mohamed-Yousef On BEST ANSWER

in your css make a default top : 0px;

div.single-column div.middle {
    padding: 10px 20px;
    clear: both;
    position: relative;
    top: 0px;
} 

and in your page you want top : 70px just add in this page

<style>
div.single-column div.middle {
    top: 70px !important;
}
<style>
0
Luca On

assuming you can edit the html:

div.single-column div.middle {
    padding: 10px 20px;
    clear: both;
    position: relative;
    top: 0; // default
}

div.single-column div.middle--alt {
    top: 70px;
} // modifier, a la BEM

in your markup on the all pages:

<div class="middle">...</div>

and on the page(s) that need top: 70px:

<div class="middle middle--alt">

if you could simplify your selectors to .middle and .middle--alt that's great, but it might not be the case as we don't know the rest of your css.

It's one of the possible 'proper' CSS way of solving your problem. However, if you can't edit the markup, see if you can use any cascading hooks (like in Praveen's answer) - otherwise you might have to use JS assuming that you can at least control what is loaded/executed on each page. Keep in mind that this kind of changes might incur in some FOUC (Flashing of unstyled content) due to the fact that your js will be likely applied after the dom is rendered and the css applied.

0
Praveen Kumar Purushothaman On

Say you are using two pages:

  • main.html
  • sub1.html
  • sub2.html

In main.html, for the <body> give a class like:

<body class="main">

And for both the sub pages, use:

<body class="sub">

And give the CSS like this:

.main .middle {top: 0px;}
.sub .middle {top: 70px;}
0
Daniel Forbes On

How about something like this:

if(window.location.href == "URL"){
document.getElementsByTagName("Body").style.top = "100px";
}else{
document.getElementsByTagName("Body").style.top = "200px";
}