I am trying to center a div with a variable width using the following code:
div {
background: red;
max-width: 400px;
position: absolute;
left: 50%;
transform: translateX(-50%);
}
While this code works well for centering, it presents an issue when the window size is reduced (for example, on smaller screens or mobile devices). In such cases, there appears to be some 'padding' around the element that takes up unnecessary space.
A different approach can be seen in this example:
Another demo without the padding issue
Please note that in the second example, the div is not centered due to its variable width. Using negative margins or JavaScript could solve this issue but I am looking for a pure CSS solution. The main goal is to avoid the 'padding' behavior when resizing the window.
Is there something missing in my implementation of translate? I want to eliminate the unwanted 'padding' around the div.