Search code examples
htmlcssmedia-queriesviewport

How to get width of device (not viewport)?


I'm making my first website and my meta tag just defines a constant width instead of taking the device width, because I am having fun with CSS animations and wanted to avoid making it dynamic. Most of it looks fine on mobile except things that need to be centered. When I center it based on percentages, it centers based on the width I set (my viewport) as opposed to the width of the device. This is not a bug, of course, but I was wondering if there was a way for me to get the width of the device even if I don't set it as the viewport, so I can just calculate the left attribute to center it. Any ideas? Thanks!

I didn't put code because there really aren't any issues, it is more of a how-to question.


Solution

  • To find the current width of your html body (device), you can try this javascript code window.innerWidth;

    Try running this code and resize your windows to different widths:

    function myFunction() {
      var wid = window.innerWidth;
      document.getElementById("display").innerHTML = "Width: " + wid;
    }
    <button onclick="myFunction()">Show</button>
    
    <div id="display"></div>

    ps: click on Run Code and then click on full page so you can resize your browser and test my snippet. It will show you the current width.