Home > database >  How to get the MAXIMUM screen width with CSS, not the current window width?
How to get the MAXIMUM screen width with CSS, not the current window width?

Time:03-03

PROBLEM

I could only find answers showing how to use vw/vh to get the current size of the window, which is not what I need.

WHAT I ACTUALLY NEED

I need the full width of the monitor screen independently of the browser window being maximized or not.

Is there a way to do this using pure CSS? If not, can it be done using JavaScript CSS? If so, how?

CodePudding user response:

CSS can only give you the viewport width, i.e. the window width. However, you can use screen.width to get the screen's width with JavaScript.

console.log(screen.width);

CodePudding user response:

do you want the content of a tag to take up the entire screen space or do you want to specifically get the height and width value in pixels? If it's the first option, I think I've found a solution.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

main {
  background: blue;

  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="./style.css">
  </head>
  <body>
    <main></main>
    <script src="./script.js"></script>
  </body>
</html>

another way to solve it would be using the innerWidth and innerHeight values of the window

const width = window.innerWidth;
const height = window.innerHeight;

const main = document.querySelector("main");

main.style.width = `${width}px`;
main.style.height = `${height}px`;
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

main {
  background: blue;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="./style.css">
  </head>
  <body>
    <main></main>
    <script src="./script.js"></script>
  </body>
</html>

A reference used: https://tutorial.tips/how-to-get-viewport-width-and-height-using-javascript/

  • Related