viery365 viery365 - 1 year ago 93
Javascript Question

Increment negative value of property based on window size

I don't know if this question has an easy or hard answer.

The situation is that I have an element on the page with negative margin:

.element {
margin-left: -195px;

It works well with a screen size 1440x532 (check with Chrome's inspector element).

What I want is kind of simple to explain.

I want an increase of 1 pixel (for instance) in the margin-left of the element anytime the window is larger by one pixel:

So, if window size is 1441, the margin-left of the element be -194px. If the window size is 1451, the margin-left of the element be -184px.

In the same way, I want this to work from 1440px upwards.

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

The Jquery solutions that other users gave you works perfectly for this use, but if you prefere you can also use a CSS-only alternative (it works even if the user has disabled scripts!).

It has got also a good support among browsers

You can implement your CSS in this way:

        margin-left: -195px;   
    @media screen and (min-width: 1440px){
            margin-left: calc(-195px + 100vw - 1440px); //100vw is the width of the screen


It adds a pixel for each pixel above 1440 Tell me if this is what you mean

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download