AlanH AlanH - 2 months ago 6
CSS Question

How do I center a div in the middle of the page, even if I change the window size?

I tried all the solutions on here, but none of them worked. I want to center this horizontally and vertically, regardless of the window size.

Note: I have my

container
div just the way I want it. It wraps around several other divs. If I adapt the changes suggested by this link, my container div gets messed up. I'm not trying have this be responsive. It's a fixed size (think an image), and I just want it to always be in the center of the window, regardless of window size.

Here's what I have:



* {
margin: 0;
padding: 0;
}
#container {
background-color: black;
border-radius: 10px;
padding: 5px;
display: block;
margin: auto;
/* changed to auto, didn't make a difference*/
border-width: 1px;
border-color: black;
border-style: solid;
position: absolute;
}
.light {
height: 100px;
width: 100px;
display: block;
border-radius: 50%;
margin: 10px;
border-width: 5px;
background-color: grey;
}

<body>
<div id="container" onclick="changeColor()">
<div id="green" class="light"></div>
<div id="yellow" class="light"></div>
<div id="red" class="light"></div>
</div>
</body>




Answer

Maybe it is not working for you as container is absolute and hence the body has zero height.

  1. Add height: 100% to html and body first.

  2. Use centering method for absolutely positioned element using transform to container:

    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    

Let me know your feedback on this. Thanks!

html,
body {
  height: 100%;
}
* {
  margin: 0;
  padding: 0;
}
#container {
  background-color: black;
  border-radius: 10px;
  padding: 5px;
  display: block;
  margin: 0 auto;
  border-width: 1px;
  border-color: black;
  border-style: solid;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.light {
  height: 100px;
  width: 100px;
  display: block;
  border-radius: 50%;
  margin: 10px;
  border-width: 5px;
  background-color: grey;
}
<body>
  <div id="container" onclick="changeColor()">
    <div id="green" class="light"></div>
    <div id="yellow" class="light"></div>
    <div id="red" class="light"></div>
  </div>
</body>

Comments