Search code examples
htmlcssflexboxpositioncss-position

How do I fix the position of elements in css regardless of the window size?


I am trying to set boxes so I can add other elements accordingly. However the positions of these boxes keep changing depending on the monitor I'm using or if I go on full screen mode on my browser.

I tried using relative units (vh, vw) for the margins but that didn't help. Here is my html and css:

.main {
  display: flex;
  position: fixed;
  height: 1036px;
  width: 1280px;
  padding: 0 96px 0 96px;
  border: 2px solid red;
  z-index: 3;
  margin: 0 300px 0 300px;
  box-sizing: border-box;
}

.header {
  position: relative;
  justify-content: center;
  align-items: center;
  height: 1036px;
  width: 528px;
  z-index: 3;
  border: 2px solid white;
  padding: 35px 0 66px 0;
  overflow: hidden;
}
<section class="main">
  <section class="header">
  </section>
</section>


Solution

  • I think you are trying to create some sort of fixed layout for your components. I think the problem is coming in cause of the fixed values you are using and misuse of position and display: flex. Try using this css code maybe it might work for you `

    .main {
      position: relative;
      height: 100vh;
      width: 100%;
      padding: 0 5%;
      border: 2px solid red;
      box-sizing: border-box;
    }
    
    .header {
      position: absolute;
      top: 20%;
      left: 10%;
      justify-content: center;
      align-items: center;
      height: 60%;
      width: 40%;
      border: 2px solid white;
      padding: 3% 0 6% 0;
      overflow: hidden;
    }
    

    `am very sure the issue is with fixed units Vs relative units