How can I use JavaScript to consistently fetch the CSS-defined percentage setting for padding/margin instead of the pixel size?

How can I retrieve the padding set in CSS for a div with {padding:10% 10px 20% 10px;} using JavaScript, considering that window.getComputedStyle(myelement).getPropertyValue('padding'); returns different results?

In Firefox, it shows as "10% 10px 20% 10px"

Meanwhile, in Chromium, it displays as "59.8839px 10px 119.768px 2px"

Is there an alternative method to obtain this information so that the percentages are retrieved instead of the current pixel values?

Link to example

var div = document.getElementsByTagName('div')[0];
console.log(window.getComputedStyle(div).getPropertyValue('padding'));

Answer №1

Hello there, friend! I wanted to share an example with you that might be helpful. Basically, the function I tested retrieves the topBottom and leftRight property styles, splits them, and concatenates them in the correct order. I hope you find it useful.

function getPaddingCSS(selector) {
    const appElement = window.getComputedStyle(document.querySelector(selector), null);
    const elementPadding = {
        topBottom: appElement.paddingBlock,
        topBottomList: appElement.paddingBlock.split(' '),
        leftRight: appElement.paddingInline,
        leftRightList: appElement.paddingInline.split(' ')
    }
    const paddingStr = `${elementPadding.topBottomList[0]} ${elementPadding.leftRightList[1]} ${elementPadding.topBottomList[1]} ${elementPadding.leftRightList[0]}`;
    return paddingStr;
}
const selector = 'navbar';
const paddingCSS = getPaddingCSS(selector)
console.log('paddingStr of ' + selector.toUpperCase() + ':', paddingCSS)
.navbar{
    padding: 3% 15px 30% 60px;
}
<navbar class="navbar"> 
</navbar>

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

Arrange the items that are missing from Array B to be located at the bottom of Array A, organized in a file tree structure

I have two arrays containing different types of objects. Each object in the arrays has a title assigned to it. My goal is to compare these two arrays based on their titles and move any files that are not included in the bottom part of the fileStructure arr ...

Web application using HTML5, AJAX, and a manifest file for offline usage

Looking for help with an issue on my website: Currently trying to put it offline. Using the manifest file: Encountering an issue with the left and right arrow navigation while offline. The browser shows an xmlhttprequest error, similar to the one found ...

Tips for disabling selection in Kendo UI grid with jQuery

Is it possible to disable the selectable attribute of a Kendo UI grid using jQuery? I have two grids - the first grid is initially set as selectable, but when changes are made to it, I want the second grid's selectable functionality to change accordi ...

Employing delegate for switching roles between classes

I'm having trouble using the jQuery delegate function to toggle classes. What I want to achieve is toggling the class of <li class="unselected-values"> to <li class="<li class="unselected-values"> when the client clicks on the label ...

Ways to store data in the localStorage directly from a server

I'm facing an issue - how can I store data in localStorage that was received from the server? Should I use localStorage.setItem for this purpose? And how do I handle storing an array in localStorage? Or am I missing something here? import { HttpCli ...

What is the best way to ensure the navigation bar stays at the top of the window once it has reached

I have a sample js fiddle provided here. The navigation bar is positioned right below the "Hello World" section, and the content follows beneath the nav bar. Is there a way to make the navigation bar stick to the top of the window once it reaches that poin ...

Encountered a 'Topology is closed' error while using EJS

After creating my profile.ejs page, I encountered an error upon reloading the page. Can someone help me understand what's causing this issue? Below is all the code I've used. My setup includes Node.js and Express as the server technologies. I cam ...

Trouble arises when the properties of this.props are supposed to exist, yet they are not

Wow, what a name. I am struggling to come up with a better title given my current state. The problem at hand is as follows: When using React, I set the state to null during componentWillMount. This state is then updated after data is fetched from a serve ...

What are some creative ways to provide video responses to a list of questions?

My task is to create a popup that includes questions and video responses. The challenging aspect for me is how to ensure each question displays a different video in the same location. Additionally, when the user first opens the popup, the initial question ...

Allow users to select options after they click a radio button

I have a pair of radio buttons and two sets of select options within different classes. Upon selecting the first radio button, the select options belonging to class1 should be enabled. On the other hand, upon selecting the second radio button, the select ...

Issue with fluid layout in CSS - Unable to specify height in pixels and minimum height property not functioning as expected

While working on a liquid layout, I have set all my width and height values in percentages. However, during the design process, I needed to check how my CSS was rendering so I temporarily set the height in pixels. Eventually, the height in percentage wil ...

Mastering the extraction of key/value pairs from a JSON response in the OnComplete ajax

After executing a specific action, it is returning the following outcome: return Json(new { result = true, value = "hello" }, "text/html"); I'm wondering how can I retrieve the value in my onComplete function? onComplete: function (file, respo ...

Guide to transforming a JSON file value into a JavaScript list

I need assistance with converting a string of comma-separated values in a JSON file into a list. The goal is to iterate through the list in a for loop and click on each element. Can you help me with this task? testdata.json : {"optionsList":&quo ...

The validator function is causing an error with the 'lowerCase()' method resulting in an undefined output

Dealing with email validation in a form, I encountered a case-insensitivity issue. Using the angular validation mustMatch to ensure emails match index for index, I needed to address the case sensitivity. This led me to create the matchCaseInsensitivity fun ...

ESLint error: EROFS read-only does not correspond to any directory

Can anyone help me with this issue? I am experiencing a problem when using Linux dual boot, but everything works fine when I use Windows. ERROR in [eslint] EROFS: read-only file system, open '/media/naufal/6878124278121004/Refactory/Skill-Test-Re ...

Utilizing Javascript to create interactive images in HTML

Is there a way for JavaScript to open the current image in a new WINDOW when an ONCLICK event occurs? <script> function imgWindow() { window.open("image") } </script> HTML <img src="pond1.jpg" height="150" size="150" alt="Johnson Pond" ...

Obtain the hyperlink reference of a loop using Jquery

I'm trying to extract web URLs from a website, but I seem to be making mistakes. I am new to working with JavaScript. I am attempting to retrieve the href elements of the a .relative tags. The 'elements' variable seems to be functioning cor ...

Guide to creating a vertical handler that can be resized

Did you know that you can resize tables in http://www.jsfiddle.net? I'm curious about how to resize just the "Vertical Handler". Could someone share the source code with me? If possible, please provide an example on http://www.jsfiddle.net. ...

Error thrown in Node.js ReadSync call due to buffer length overflow

I am working on generating RTP packets for an MJPEG video. My process involves reading the first 5 bytes of the file to determine the frame length, and then reading that specified size. Below is the code snippet I have implemented: while(totalSiz ...

How can I gather information from members who have already signed up?

I have a form that submits data to the Angular Firebase database. Once the form is submitted, I want to display the previously submitted data in the form if the user signs in again. Below is my .ts file: import { Component, OnInit } from '@angular/c ...