Matching Javascript Variables to CSS Styles

I am currently developing a small HTML page and I am utilizing JavaScript to retrieve the screen dimensions. However, I am facing an issue with passing this variable to a CSS style as shown below. How can I achieve this successfully? Additionally, I have observed that "px" needs to be appended at the end of the value for proper formatting, such as top: 100px instead of top:100. How can I incorporate this into my variable adjustment? Any assistance on this matter would be greatly appreciated.


<script type="text/javascript>
var percent =1;
var myWidth = Math.round(screen.width * percent);
var myHeight = Math.round(screen.height * percent);
</script>

<style type="text/css">
div.content {
    margin: auto;
    top: myHeight + 'px';
    width: myWidth + 'px';
}
</style>

Answer №1

To incorporate LESS CSS, experiment with the following code snippet:

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

If you are considering using JQUERY, test out this code instead:

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

If your preference is for JS, give this code a try:

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';

Answer №2

If you're working with vanilla JavaScript, one approach is to fetch all div elements using the getElementsByTagName method and then narrow down the selection based on their class names such as content.

For modern browsers (especially for those stubborn IE versions):

  • An alternative could be employing the getElementsByClassName function to target only divs within the document.
  • You may also utilize the querySelectorAll method that directly gives you a collection of matching elements.

Subsequently, iterate over each matched element and apply the following style changes:

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

Answer №3

let dynamicCss = "div.container { margin: auto; top: " + 
    customHeight + "; width: " + customWidth + " ; }";

let customStyle = document.createElement('style');
customStyle.type = 'text/css';
customStyle.styleSheet ? customStyle.styleSheet.cssText = dynamicCss : 
    customStyle.appendChild(document.createTextNode(dynamicCss));

document.getElementsByTagName("head")[0].appendChild(customStyle);

This code snippet generates a unique style element as specified and attaches it to the head section of the HTML document, thereby applying the styles.

Answer №4

jQuery is compatible with all web browsers, including Internet Explorer, although it requires jQuery to function properly. Meanwhile, JavaScript is supported by most browsers except for Internet Explorer. Alternatively, Pure CSS can be used as a fallback in case JavaScript is disabled. Choose the solution that suits your needs 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%;
}

Answer №5

Have you thought about incorporating a tool such as LESS? It might be worth exploring, depending on your needs and preferences.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript has issues with undefined array elements

Even though there is data in bindInfo, the array elements in Bind are showing as undefined. Any recommendations? let bindinfo = { clientid: 1, clientname: 'Web Client', nowutc: now_utc, bindlist: Bindings(this.props.bindDetails) ...

Conceal only the anchor tag's text and include a class during the media query

In the anchor tag below, I have a text that says "Add to cart," but on mobile view, I want to change it to display the shopping cart icon (fa fa-cart). <a class="product"><?php echo $button_add_to_cart ?></a> Currently, the variable $bu ...

Library written in JavaScript for extracting CSS that is relevant

Is there a JavaScript tool available that can extract the style information from HTML code? For instance, when given the following HTML snippet, it would output a style block containing all the computed styles applied to each of those elements? Input... ...

After subscribing, my Angular template fails to refresh

Currently, I am facing an issue with my Angular 17 project where the data fetched from the API is not updating the template. This means that despite receiving the data, I am unable to display it on the page. The code snippet below shows the service compon ...

Hiding Modal Box Upon User Login: A Step-by-Step Guide

After a user clicks the login button in my navigation, a modal box pops up. However, once the user logs in, the modal box does not disappear. How can I hide or remove the modal box when users click on the login button? This code snippet is from Home.vue: ...

Ensure that the body background image remains stretched and perfectly centered regardless of the screen resolution

I am having an issue with vertical centering on a website I created. Everything looks fine on my monitor, but at higher resolutions, the tables don't align in the center and the image shrinks. How can I ensure that everything stays aligned properly? ...

"Simultaneously creating a Firebase user account and populating the database with user

My goal is to store new user information in my database using their unique user UID when they sign up through Firebase. Currently, my code is functioning properly, however, I am facing an issue where the name (which should be the created user UID) appears ...

Incorporate a comma after the second or third digit to separate currency values in JavaScript

Is there a way to add commas to currency values at the 3rd or 2nd place depending on the value itself? The desired output format is: 1000 => 1000 10000 => 10,000 210000 => 2,10,000 2010000 => 20,10,000 12010000 => 1,20,10,000 I am currentl ...

I am struggling to retrieve a value from the angular.forEach function, the flag value is not being obtained. What could be

I'm having an issue with my controller.js file. I can't seem to access the value from the angular.forEach function, specifically the flagvalue isn't being retrieved. Is it because the scope of flagvalue ends when the forEach function complet ...

Using Vue JS to display information conditionally within a single component

I currently have a component that dynamically displays the data from an array of objects. However, I want the component to display only one object based on a specific condition. Is it possible to show either one object or another depending on the value o ...

The col-md-4 class in Bootstrap does not consistently maintain a width of 33%

Currently, I am utilizing bootstrap cards in my project. The number of cards within a card-deck varies dynamically. However, I have encountered an issue where each card should occupy a width of col-md-4 (33%). Everything works fine when there are more than ...

Exploring the Power of Websharper with Sitelets and Forms

I have been working on developing a form using Websharper to gather user input. Currently, I have identified three actions for my website: type MyAction = | [<CompiledName "">] Index | [<Method "POST">] GetUser of username : string ...

Implementing cross-app module injection in Node.js

I have two node apps/services that are currently running together: 1. the main app 2. the second app The main app is responsible for displaying all the data from different apps in the end. Currently, I have taken some code from the second app and integra ...

Tips for aligning two elements in a row using Bootstrap 4 Flex

I am facing a challenge with positioning an H2 element and a Dropdown button on the same line using bootstrap 4 flex. Here is what I have: https://i.sstatic.net/kV45k.png This is what I am trying to achieve: https://i.sstatic.net/Owt5j.png Below is my ...

The event is not triggered by ng-submit

I'm struggling with submitting this form. I've checked everything, but it just won't work. This is my HTML: <html ng-app = 'myApp'> <div ng-controller="Tabs"> ... <form ng-submit="sendClicked()" &g ...

Guide on inserting a new user to the db.json

My database file, db.json, has the following structure: { "users": [ { "id": 0, "isActive": true, "balance": "$2,309.20", "picture": "http://placehold.it/128x128", "age": 26, "accessLevel": "guest", "firstNa ...

Alter the color of H3 when clicked and then gently fade it back

Is it possible to create a button on the top of my webpage that scrolls to a specific DIV when clicked, and also have it change the color of an h3 element once it has scrolled to it? This effect is similar to how Facebook highlights notifications. This is ...

The customized icon in the Material UI Select component lacks proper vertical centering

Check out this demo link where the dropdown icon is currently not vertically centered. It appears to have extra top padding due to the class "tlm-dropdown-icon", causing it to be off-center. I've tried inspecting the element but couldn' ...

The bodyparser in Express seems to be malfunctioning

When configuring my body parser, I implement the following code: const express = require('express') const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extend ...

Props and theme merge to create uniquely designed styled components with a thematic twist

Out of sheer curiosity, I've been incorporating styled-components into my React application. Within this framework, I make use of the recommended theme to ensure consistency in colors and sizes throughout. Currently, my approach looks something like ...