How to set dynamic CSS value using JavaScript

I want to have a responsive add- divon for on my page. It should be the fifth part height, which is in the variable cover_height.

This is my approach so far, which follows the answer to this question , but it does not change padding-top:

var cover = document.getElementById("cover");
var cover_height = cover.height;    

cover.style["padding-top"] = cover_height / 5 + "px";

Any feedback on the code is appreciated since I'm pretty new to JS.

+4
source share
2 answers

JavaScript (vanilla) element.height, . .clientHeight .offsetHeight , . offsetHeight , , .

var cover = document.getElementById("cover");
var cover_height = cover.clientHeight;

cover.style["padding-top"] = cover_height / 5 + "px";
#cover {
  height: 300px;
  background: red;
}
<div id='cover'></div>
Hide result

?

viewport height, - . ( ) , padding-top 1/5- . , 100px, 30px, 6px.

#cover {
  height: 30vh;
  background: red;
  padding-top: 6vh;
}
<div id='cover'></div>
Hide result

(), , padding-top.

padding-top , CSS . , padding margin . .

+5

clientHeight offsetHeight height.

  • clientHeight: .

  • offsetHeight: , .

:

var cover = document.getElementById("cover");
var cover_height = cover.clientHeight;    
//OR
var cover_height = cover.offsetHeight;    

cover.style.paddingTop = cover_height / 5 + "px";

, .


var cover = document.getElementById("cover");
var cover_height = cover.clientHeight;    

cover.style.paddingTop = cover_height / 5 + "px";
#cover{
  width: 200px;
  height: 200px;
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cover'> Cover </div>
Hide result
+2

All Articles