flexboxalignmentvertical-alignment

top 50% and translateY(-50%) not working as expected


I am trying to vertically align the div using the age old technique of

top: 50%; transform: translateY(-50%);

but it is not working as I expect it to. I am wondering what the problem here could be.

I tried adding display flex to the body and adding align-content: center; but that just jumbles everything. So I tried the aforementioned technique but it's just placing the div halfway up the screen without the top: 50%; affecting it at all.

Here's the code:

body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

#mittrek {
  width: 80%;
  max-width: 200px;
  height: 400px;
  border-radius: 20px;
  z-index: 10;
  background-color: rgba(0, 0, 0, 0.5);
  position: relative;
  margin-left: auto;
  margin-right: auto;
  top: 50%;
  transform: translateY(-50%);
  backdrop-filter: blur(15px);
  -webkit-backdrop-filter: blur(10px);
  background-repeat: no-repeat;
  display: flex;
  align-content: center;
  justify-content: center;
}

#mittrek::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 4px;
  border-radius: 20px;
  mask-composite: exclude;
  z-index: 4;
  overflow: hidden;
  box-shadow: 0px 0px 40px 15px black;
}
<!DOCTYPE html>

<html>
<body>
  <div id="mittrek"></div>
</body>
</html>


Solution

  • You set wrong value of position property for mittrek. This is updated code.

    <!DOCTYPE html>
    
    <html>
    <head>
      <style>
        body {
          margin: 0;
          padding: 0;
          overflow: hidden;
        }
    
        #mittrek {
          width: 80%;
          max-width: 200px;
          height: 400px;
          border-radius: 20px;
          z-index: 10;
          background-color: rgba(0, 0, 0, 0.5);
          position: absolute; // Changed relative to absolute
          margin-left: auto;
          margin-right: auto;
          top: 50%;
          left: 50%; // Added left
          transform: translate(-50%, -50%); // Changed translateY to translate
          backdrop-filter: blur(15px);
          -webkit-backdrop-filter: blur(10px);
          background-repeat: no-repeat;
          display: flex;
          align-content: center;
          justify-content: center;
        }
    
        #mittrek::after {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          padding: 4px;
          border-radius: 20px;
          mask-composite: exclude;
          z-index: 4;
          overflow: hidden;
          box-shadow: 0px 0px 40px 15px black;
        }
      </style>
    </head>
    <body>
      <div id="mittrek"></div>
    </body>
    </html>
    

    result-image