How can CSS get the width of a window in px?

86 Views Asked by At

I'm currently trying to write code that centers a website for which the content is exactly 895 pixels wide, and I want it to be centered. So, I'm trying to write the following in CSS:

body {
...
     padding-left: calc(([window width] - 895) / 2);
}

Is there a command which does that? is there a better way of doing this?

I have tried the following variable names: view-width vw screen screen.width screen-width

2

There are 2 best solutions below

0
On

While I did not find how to make that specific bit of code work, I found another method of centering my website; I did so with:

body {

. . . 

margin: 0 auto;

}
1
On

For window width you can use 100vw, which actually means "100% of viewport width". You can mix that with px units inside a calc formula.

So the padding setting in your question would be written as

padding-left: calc((100vw - 895px) / 2);