skip to Main Content

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

3

Answers


  1. Chosen as BEST ANSWER

    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;
    
    }
    

  2. 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);
    
    Login or Signup to reply.
  3. Try the following code snippet,

    body {
      padding-left: calc((100vw - 895px) / 2);
      max-width: 100%;
      box-sizing: border-box; /* Ensures padding is included in the total width */
    }
    
    @media (max-width: 895px) {
      body {
        padding-left: 0;
      }
    }
    

    You can use the calc() function along with vw to achieve a proportional width. You can add a media query to handle smaller viewport widths differently if needed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search