# Absolutely Positioned Element That Lines up with left margin of a max-width element.

Updated: Nov. 11, 2021 Skip to Best Solution »

Adjust the width of this window.

This box has a max-width of 500px , while the title above is absolutely positioned.

But they always line up.

This is accomplished by usign CSS Calc to calculate the padding-left of the text box above.

The math is actually pretty simple. We take the full width of the viewport minus the max width, and divide that by two.

Here's what the code looks like...

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

There's only one tiny problem.

Scroll bars.

They mess up this lovely formula. So you have to remove 8 extra pixels to make it perfect, like this...

`padding-left:calc( (100vw - 500px) / 2 - 8px);`

## Improved Solution!!! (Nov. 11, 2021)

Until now, scroll bars were the Achilles' heel of this code.

Previously you were forced manually remove 8px to account for the standard 17px scrollbar. But adjusting 8px for the scrollbar isn't ideal because you're assuming there will be a 17px wide scrollbar.

That assumption is far from certain. Some browsers have floating scroll bars (like smartphones or Safari on MacOS) and short pages (or tall screens) might not have scroll bars at all.

So, here's a better solution!

You can actually get the viewport width minus the scrollbars with the following equation that I found on Stack Overflow .

`width: calc(100vw - (100vw - 100%));`

However, this only works if the element you are sizing is a direct child of body, or an element that has the same width as body.

That is, unless you use a CSS Variable.

Create a CSS variable on the body, as shown below...

`body { --screen-width:calc(100vw - (100vw - 100%)); }`

Then use it anywhere it is needed. Here's an example...

`.textbox { padding-left: calc( ( var(--screen-width) - 500px) / 2); }`

The code works on pages with scroll bars or without scroll bars, with zero need for javascript.

What do you think? Did I miss anything?

Feel free to comment on this pen with your thoughts.