简体   繁体   中英

Change an element width in px when resizing the window

How can I change an element with a fixed width in px when i resize the window? I need to use an absolute unit, i can not use relative units like % or vw.Every time the window is resized with 1 px i need to decrease the element width by 0.2px.

I tried to use the window resize eventListener but i don't know what calculations needs to be done.

What you want can be achieved by using javascript. I've created a logic to do that :

<script>
        function myFunction() {
            var initialscreenwidth = window.innerWidth;         //Set Initial Screen Width
            setInterval(function() {        //looping the script
                var screenwidth = window.innerWidth;
                var difference = initialscreenwidth - screenwidth;      //Calculating the change in screen-size

                if (difference != 0) {                                  //Checking if there is a change in width
                    var element = document.getElementById('demo');
                    var style = window.getComputedStyle(element, null).getPropertyValue('font-size');       //Getting default font-size of the element
                    var initialfontsize = parseFloat(style);
                    var fontdifference = -(parseFloat(difference) / 5);           //1px change in screen-size = 0.2px change in font-size
                    var newfontsize = initialfontsize + fontdifference;
                    var newfontsizepx = newfontsize + "px";

                    if (newfontsize > 1) {
                        document.getElementById("demo").style.fontSize = newfontsizepx;
                    }
                }
                initialscreenwidth = window.innerWidth;
            }, 300);    //reloads in every 300ms 
        }
        myFunction();

    </script>

Paste this at the end of your body section, somehow using this in the head section is not working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM