viery365 viery365 - 1 year ago 55
Javascript Question

Increment negative value of property based on window size by less than 1px

This question is very similar with other.
The only difference (and for me is a huge difference because I cannot figure it out) is the value of the CSS value increment.

I have an element on the page with negative margin and in the other question I wanted it to increment by 1 pixel each time the screen was larger by 1 pixel, starting on 1400px wide upwards.

.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 of the element should be -194px or if the window size was 1451px wide the margin-left of the element should be -184px and so on.

The answers were awesome and I got it resolved (with CSS or javaScript).

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

However now that is implemented I noticed that instead of 1 pixel the element's margin needs only 0.1 pixels of increment:

So:

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

If the window size is 1441px wide the margin-left of the element should be -194.9px

or if the window size is 1452px wide the margin-left of the element should be -193.8px and so on.

Starting at 1400px wide upwards.

I am aware that the questions are very similar. However I feel this one is a different level somehow.

IMPORTANT NOTE: What I want is a dynamic value for the margin-left that increases based on screen size and not a kind of media query which would make the value always remain the same between an interval of screen sizes. What I want would force me to add a massive number of media queries.

Is this possible with javaScript or jQuery? (or even CSS?)

Answer Source

CSS version:

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

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

CODEPEN EXAMPLE (CSS)

CODEPEN EXAMPLE (JS)