Skip to content Skip to sidebar Skip to footer

Javascript Variable To Css

I am working on a small html page. I am using javascript to get the dimensions of the screen. I need to pass that variable to a css style like below. How can I do this? Also I noti

Solution 1:

If you intend to use LESS CSS you can try out this :

    @percent: 1;
    @height: `Math.round( screen.height * @{percent})`;
    @width: `Math.round( screen.width * @{percent})`;
    div.content {
    margin: auto;
    top: @height;
    width: @width;
    }

If you intend to use JQUERY you can try out this :

var percent=1;
$("div.content").css('top', Math.round( screen.height * percent)+'px');
$("div.content").width(Math.round( screen.width * percent));

If you intend to use JS you can try out this :

var percent=1;
document.querySelector('div.content').style.top = Math.round( screen.height * percent)+'px';
document.querySelector('div.content').style.width = Math.round( screen.width * percent)+'px';

Solution 2:

With pure JS, you could get all div via getElementsByTagName, then filter for a content class name.

For newer browsers (most especially for IE):

Then for each that match, do:

currentDiv.style.top = myHeight;
currentDiv.style.width = myWidth;

Solution 3:

jQuery works with all browsers, even Internet Explorer, but you need jQuery. The JavaScript works with all browsers, except for Internet Explorer. Alternative you could use pure CSS, which works when JavaScript is disabled. Try whichever works best :).

JavaScript

var width = body.offsetWidth;
var height = body.offsetHeight;
var _content = document.querySelectorAll(".content");
content.style.width = width + "px";
content.style.height = height + "px";

Or jQuery

var width = $(document).width();
var height = $(document).height();
var _content = $('.class');
content.style.width = width + "px";
content.style.height = height + "px";

Or CSS

.content {
    margin:auto;
    top:100%;
    width:100%;
}

Solution 4:

Also you could consider using something like LESS Not sure if this is an option for you or not.


Post a Comment for "Javascript Variable To Css"