Converting units to rem dynamically in CSS: a comprehensive guide

Hey there, I'm currently trying to dynamically convert units into rem in CSS and facing some issues.

  1. I have set the root font-size as 23px
  2. The current font-size is 16px
  3. The expected result should be 16 / 23 => 0.695rem

Question: I am looking for a way to perform this calculation in CSS - 16 / 23 => 0.695rem, however, it is not working correctly.

This is how I attempted to implement it using CSS:

#im_p{
    font-size: calc(var(--im-p-font / 16)) rem;
}

Here's what I have tried so far:

const root = document.documentElement;

root.style.setProperty('--im-p-font',23);
#im_p{
  font-size: calc(var(--im-p-font / 16)) rem;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0>
    <title>Document</title>
</head>
<body>
    <p id="im_p">I'm Paragraph<p>
</body>
</html>

Note: The above CSS code snippet is not functioning as expected.

Answer №1

One issue lies in the CSS calc format.

Ensure that brackets are properly matched (var requires matching brackets) and include rem as a multiplier within the calc:

  font-size: calc((var(--im-p-font) / 16) * 1rem);

const root = document.documentElement;

root.style.setProperty('--im-p-font', 23);
#im_p {
  font-size: calc((var(--im-p-font) / 16) * 1rem);
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <p id="im_p">I'm Paragraph
    <p>
</body>

</html>

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

Error message displayed in Ajax jQuery shows '[object Object]'

There seems to be an issue with this code on certain computers. I have a basic AJAX call set up to display a list of batches in a select tag. function show_batch(class_id,batch_id){ if(class_id){ $.ajax({ url:root_path+"module/fee_ ...

Is there a way to iterate through an array in reverse, starting from the last element and ending at the first element?

Is there a way in JavaScript to map an Array starting from the last index and going all the way to the beginning descending, without iterating from the beginning index? I'm looking for a more efficient method or feature I might have overlooked. Any s ...

Redeem your Paypal discount code at checkout

I'm in the process of creating a simple product checkout system for my website. I've implemented PayPal's default checkout system, which works well, but I also want to include a coupon code feature. Unfortunately, I couldn't find an opt ...

What is the best way to transfer a PHP string to JavaScript/JQuery for use in a function?

Within my PHP code, I have the following: $welcome = "Welcome!"; echo '<script type="text/javascript">addName();</script>'; Additionally, in my HTML/script portion: <a id="franBTN"></a> <script type="text/javascript ...

Ways to clear the time attribute from an ISO DateTime in date format

How can I remove the time attribute from a date in the format 2016-05-24T05:07:57.756Z and set it to something like 2016-05-25T00:00:00.000Z? Any assistance would be greatly appreciated. ...

Issue: 040A1079 - Failure in RSA Padding Check with PKCS1 OAEP MGF1 Decoding Error Detected on Amazon Web Services

Utilizing the crypto package, I execute the following tasks: Using crypto.generateKeyPairSync() to create publicKey and privateKey The keys are generated only once and stored in the .env file Applying crypto.publicEncrypt() to encrypt data before savin ...

Modification of encapsulated class in Angular is not permitted

Within Angular, a div element with the class "container" is automatically created and inserted into my component's HTML. Is there a way to modify this class to "container-fluid"? I understand that Angular utilizes encapsulation, but I am unsure of how ...

jquery sequential fade effect

I am trying to make each div fade in one by one. Visit this link for reference <div id="w"> <div class="one"></div> <div class="two"></div> <div class="three"></div> </div> $(function() { $(&a ...

What could be causing this jQuery to malfunction?

Having trouble with the functionality of hasclass and this.addclass. if ($('.sidebar-menu-container li').hasClass('current-menu-item')) { $(this).addClass('expanded'); } Check out this CodePen for reference. ...

Oops, the element type specified is not valid. Make sure to use a string for built-in components when working with NextJs

I am incorporating SVG's as a component in my nextjs application, but I encounter the following error message: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. ...

Unable to display toast notification in React/MUI/Typescript project

Currently tackling error notifications targeted at 400,401, and 500 errors within a large-scale project. I am facing an issue where I want to integrate my ErrorToastNotification component into my layout.tsx file to avoid duplicating it across multiple page ...

How to create a WordPress sidebar that remains fixed while scrolling

I have a WordPress website with a right sidebar that I want to make sticky while scrolling up and down. I applied some CSS styles to achieve this, and now the sidebar is sticky. However, the issue is that it keeps shifting its position from right to left. ...

Attempting to reveal the gridview that has been hidden due to a server-side command

I am attempting to make the gridview visible that is hidden by the server side on page load method in C#. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.BindDummyRow(); } ...

Considering the development of a web application similar to Canva

I'm interested in creating an app similar to Canva, but I'm not sure where to begin. I have a solid understanding of HTML and CSS, but my JavaScript skills are basic. I'm curious about the technologies they use. Is there a way to save HTM ...

Sidebar Text Remains Visible Despite Collapsed Sidebar

I'm working on implementing a sidebar shrink effect when collapsing it using a combination of custom CSS, jQuery, and Bootstrap. The custom CSS and jQuery handle the shrinking effect, while Bootstrap is used for styling purposes. However, I am facing ...

Facing issues with React JS and Material UI? If you're encountering problems where 'this.props' is

After running the code provided below, I anticipated that the styles would be injected within props. However, I consistently encounter undefined props. No props are being supplied to this component. const customStyles = theme => ({ root: { & ...

The images in the React slick carousel appear to be slightly out of

I'm experiencing blurriness in my carousel when it animates with card items. Despite searching for a solution, I haven't found one yet. My tech stack includes Next.js and TypeScript. const ref = useRef<any>(); const settings = { arro ...

Challenges with incrementing in Jquery's each loop and setTimeout

http://jsfiddle.net/fxLcy/ - an example showcasing the use of setTimeout. http://jsfiddle.net/fxLcy/1/ - this demo does not include setTimeout. Although all elements are correctly positioned, I am in need of that delayed animation =/ My goal is to arrang ...

Adjusting the gap between TableRows in Material-UI

Is there a way to increase the spacing between TableRow MaterialUI components in my code? <S.MainTable> <TableBody> {rows.map(row => { return ( <S.StyledTableRow key={row.id}> <TableCell component="th" s ...

Creating a JSON file using an object to send requests in Angular

In my Angular 7 project, I am trying to send a multipart request to the server that includes a file (document_example.pdf) and a json file containing a data object (data_object_example.json). The content of data_object_example.json is as follows: { " ...