Keep margin of absolute positioned and centered div on window resize

298 views Asked by At

I have few divs on my page, which serve as a containers. Here is a sample CSS code of one of the divs:

header {
    background-color: #fff;
    height: 153px;
    width: 97%;
    min-width: 1084.06px;
    margin: 15px auto;
    position: absolute;
    left: 0; 
    right: 0;
    border-radius: 20px;
}

This is a centered container for my header. There are several other containers which I have styled simillar way (absolute, centered and width in %).

Problem is, when I resize the window, all these containers hit the left side of the browser window. I want to save some margin on particular window width. How can I achieve that?

P.S. If I add margin-left it breaks my center position of the div

2

There are 2 answers

0
Coomernatior On

Add another margin-right then straighten it out depending on what you use

0
Tha'er AlAjlouni ثائر العجلوني On

You can use media queries, media queries are only applied on specific conditions, such as a specific width.

For example the following background-color rule won't apply for screens wider than 480px:

@media screen and (max-width: 480px) {
  body {
    background-color: lightgreen;
  }
}

For more info about media queries see this w3schools page