Increase the negative property value by a fractional amount depending on the size of the window

This question is quite similar to another one I came across. The main difference that's stumping me is the CSS value increment.

In the previous question, there was an element on the page with a negative margin, and I wanted it to increase by 1 pixel each time the screen size increased by 1 pixel, starting from 1400px wide and up.

.element {
margin-left: -195px;
}

So, if the window size was 1440px wide, the margin-left of the element should be -195px. If the window size was 1441px wide, the margin-left should be -194px, or if it was 1451px wide, the margin-left should be -184px, and so forth.

The responses were fantastic and helped me resolve it using CSS or JavaScript.

.........................

However, after implementing the solution, I realized that instead of a 1-pixel increment, the element's margin actually needs only a 0.1-pixel increment:

So:

If the window size is 1440px wide, the margin-left of the element should be -195px.

If the window size is 1441px wide, the margin-left should be -194.9px.

Or if the window size is 1452px wide, the margin-left should be -193.8px, and so on.

Starting at 1400px wide and up.

I understand that these questions are very similar, but this one seems to present a new challenge.

IMPORTANT NOTE: What I need is a dynamic margin-left value that increases based on screen size, rather than being fixed within a range of screen sizes through media queries. Implementing a huge number of media queries is not an option for me.

Is this achievable with JavaScript, jQuery, or even CSS?

Answer №1

This is the CSS version:

@media screen and (min-width: 1440px) {
  .element {
    margin-left: calc(-195px + (100vw - 1440px) * 0.1);
  }
}

And here is the JS version:

var element = $('.element'), windowWidth, x;

$(window).resize(function () {
  if ($(window).width() > 1440) {
    windowWidth = $(window).width();
    x = (windowWidth - 1440) * 0.1;
    element.css('margin-left', -195 + x);
  } else {
    element.css('margin-left', -195)
  }
});

$(window).trigger('resize');

Check out this CODEPEN EXAMPLE for CSS styling.

And here's a CODEPEN EXAMPLE for Javascript implementation.

Answer №2

While this code may be functional, there are potentially better approaches to achieve the desired outcome...

var elements = document.getElementsByTagName('element');

window.onresize = function(){
  if (window.innerWidth >= 1400) {
    var margin, i;
    margin = -195 - (0.1*(window.innerWidth - 1400));
    for (i=0; i < elements.length; i++) {
      elements[i].style.marginLeft = margin + "px";
    }
  }
}

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

Has the user successfully authenticated with Google?

Possible Repetition: How to verify if a user is logged into their Google account using API? I'm working on a website that displays a Google Calendar. My query is: Can I determine whether a user is currently logged into a Google Account? If it&ap ...

Choose a specific Div element in JQuery without unintentionally selecting its parent Div

Here is a script I am currently working with: $("#border-radius").click(function(){ var value = $("#border-radius").attr("value"); $("div.editable").click(function () { mySQLinsert(value, '2', this.id) $(this).css({ "-webkit ...

Stop const expressions from being widened by type annotation

Is there a way to maintain a constant literal expression (with const assertion) while still enforcing type checking against a specific type to prevent missing or excess properties? In simpler terms, how can the type annotation be prevented from overriding ...

Verifying the presence of various strings across multiple files

I am faced with the task of identifying missing translations in a JSON object, which may contain nested JSON objects. Here is an example of the JSON file I am working with: const translations = { lang: 'en', data: { 'NAV&apos ...

Having trouble with PHP when using JQuery Ajax to post data

Currently, I am working with a list of records retrieved from a MySQL table. Each record has been assigned an onclick function to pass data for further database queries without having to refresh the page. <a href='javascript:void(0)' onclick= ...

Guide to adding information to an .xml document

Currently, I am working on building a website for a school project, specifically an online shop. I am focusing on the shop section, where I need to store data such as name, price, image, and description in either a text file or XML format. Right now, the w ...

What is the best way to retrieve the value stored in the key "headerText" from a JSON object and display it in the result div?

If I have a JSON file, I would like to show the headerText value in the results div when a user picks an option from the dropdown menu provided by the JSON: HTML <div id="result"></div> <select id="dropdown"> <option value="">Sele ...

What are the best practices for maximizing the efficiency of bootstrap-sass?

Currently, I am exploring npm modules and came across bootstrap-sass. After downloading the modules, I was seeking a solution to compile scss into the static folder of my application, as well as the js bootstrap files. However, after checking the npmjs do ...

Unable to use .ajax within autocomplete function

I've been struggling for days to make the jQuery autocomplete feature work. Currently, I am able to type in the textbox and see exactly what I want, but the issue arises when I click on the desired option - it does not show up in the textbox. I suspec ...

JavaScript vs. GSP: Exploring How to Trigger a Grails Action

There is an action in a controller that I need to modify. def deleteFiling={ obj.removeFiling() redirect(action:"list") } This action is triggered from a GSP: <g:link action="deleteFiling" id="${filingInstance.id}"> <img src="${resource(di ...

The ellipsis feature is malfunctioning when applied to labels

Hey there, I'm looking to style my label with an ellipsis effect that is inside a UL element. I have tried adding max width and min width for the UL, along with ellipsis and overflow hidden for the label. However, this causes the label content to be p ...

Combining Multiple Arrays into a Multidimensional Array

I'm struggling to find information on how to combine multiple arrays of the same length into a multidimensional array. For example, I have three arrays: array1 = [value1a1, value2a1, value3a1]; array2 = [value1a2, value2a2, value3a2]; array3 = [value ...

Zod handling the visual component

I am currently working on a project using react-file-base64 to handle file metadata such as name, type, size, and base64 encoding. Despite registering zod validation, I encountered an "image required error" even after uploading the image. Upon investigatio ...

Is it possible for a prop to change dynamically?

I am currently developing a component that is responsible for receiving data through a prop, making modifications to that data, and then emitting it back to the parent (as well as watching for changes). Is it possible for a prop to be reactive? If not, wh ...

Utilizing JsSIP in a real-world telephone device

After reviewing the JsSIP library, I found it to be quite promising. However, one downside is that there doesn't seem to be an actual demonstration or code provided for making calls to a mobile phone. My question is whether it's possible to call ...

Calculate and retrieve the result from the event handling function

I need to capture a returned value and store it in a variable within an event handler function. Below is a sample code snippet demonstrating this: var xhr = new XMLHttpRequest(); function getData(e) { if (xhr.readyState === 4) { if (xhr.s ...

Why do users struggle to move between items displayed within the same component in Angular 16?

Lately, I've been immersed in developing a Single Page Application (SPA) using Angular 16, TypeScript, and The Movie Database (TMDB). During the implementation of a movies search feature, I encountered an unexpected issue. Within the app\servic ...

Running a Python script through a Javascript event

I'm looking to enhance my webpage by implementing a feature where users can generate a personalized QR code with the click of a button. My current setup involves a Python script that creates the QR code image and saves it as a .png file. I want to int ...

Using a for loop to create visualizations using amCharts in JavaScript

Is there a more efficient way to generate multiple line charts simultaneously? I've tried using the code below, but it's not working as expected. Any suggestions on how to generate graphs using looping mechanisms like for/while loops? I have a la ...

Creating a collapsible sidebar feature in Angular 2

Currently in the process of converting an HTML jQuery AdminLTE dashboard to Angular 2 In the past, I would hide and show the sidebar using toggle() in jQuery. Now I'm wondering how to achieve the same functionality in Angular 2. I am utilizing the ...