Search code examples
htmlcssimagecenter

how to center an image inside form?


Hello, I want to center an image inside the form
I used position: absolute to make it in center but didn't work

 position: absolute;
  left: 50%;
  top: 50%;

like this: enter image description here

I've tried this code so far:

body {
  top: 0;
  padding: 0;
  left: 0;
  margin: 0;
  height: 100vh;
  width: 100%;
  font-family: Arial;
  position: relative;
  background: linear-gradient(48deg, #1f3347 50%, #2c4050 50%);
}
.from_body {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  height: 390px;
  width: 400px;
  border-radius: 10px;
  border-top-left-radius: 50%;
  border-bottom-right-radius: 50%;
  border: 1px solid #2980b9;
}
.from_body img {
  height: 120px;
  width: 120px;
  position: absolute;
  left: 33%;
  margin-top: -67px;
}
.from_body .text {
  font-size: 30px;
  font-weight: 600;
  color: white;
  margin-left: 120px;
  margin-top: -5px;
  border-bottom: 2px solid;
  border-radius: 3px;
  width: 160px;
}
<body>
    <div class="form_body">
        <img
            src="https://pngset.com/images/google-contacts-icon-google-contacts-icon-disk-dvd-symbol-number-transparent-png-2734641.png">
        <p class="text">User login</p>
    </div>
</body>

I'm a beginner and I would appreciate any help!


Solution

  • The PNG in OP didn't look like it was transparent so I got one that does. The body has flexbox properties, <div>s are replaced by a <figure> and <figcaption> for semantics. The <img> will conform to the dimensions of the <figure> due to object-fit: contain.

    body {
      display: flex;
      flex-flow: column nowrap;
      justify-content: center;
      align-items: center;
      min-height: 100%;
      width: 100%;
      font: 3ch/1 'Segoe UI';
      background: linear-gradient(48deg, #1f3347 50%, #2c4050 50%);
    }
    
    figure {
      width: max-content;
      margin: 0 auto;
    }
    
    figcaption {
      text-align: center;
      color: #fff
    }
    
    img {
      object-fit: contain;
    }
    <body>
      <figure>
        <img src="https://9to5google.com/wp-content/uploads/sites/4/2017/05/google-contacts.png">
        <figcaption>User Login</figcaption>
      </figure>
    </body>