-2

I have an element with an image inside and I want to center it. I'm using position: absolute but it does not work properly. Here is the code:

<div class="wraper">
  <div class="main"><img src="image.jpg" alt=""></div>
</div>

.wrapper {
  position: relative;

  .main {
     margin-top: -157px;
     margin-left: -157px;
     position: absolute;
     top: 50%;
     left: 50%;
     width: 314px;
     height: 314px;
     line-height: 314px;
     background: #000;
     border-radius: 50%;
     text-align: center;

     img {
       vertical-align: middle;
     }
  }
}

And here is the image: enter image description here

Turnip
  • 35,836
  • 15
  • 89
  • 111
Andy N.
  • 7
  • 2

2 Answers2

0

You are using misspelled class name in HTML:

<div class="wraper">
               ^^---- it should be wrapper

And you will need to add height: 100% as well. i.e:

html,
body,
.wrapper {height: 100%;}

html,
body,
.wrapper {height: 100%;}

.wrapper {
  position: relative;
}

.main {
  margin-top: -157px;
  margin-left: -157px;
  position: absolute;
  top: 50%;
  left: 50%;
  width: 314px;
  height: 314px;
  line-height: 314px;
  background: #000;
  border-radius: 50%;
  text-align: center;
}

img {
  vertical-align: middle;
}
<div class="wrapper">
  <div class="main"><img src="image.jpg" alt=""></div>
</div>
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
0

You need to set the height of all ancestors to 100% otherwise they will collapse to zero and the result will look like your screenshot.

JSFiddle

html, body {
  height: 100%;
  min-height: 100%;
  margin:0;
}
.wrapper {
  height: 100%;
  position: relative;

  .main {
     margin-top: -157px;
     margin-left: -157px;
     position: absolute;
     top: 50%;
     left: 50%;
     width: 314px;
     height: 314px;
     line-height: 314px;
     background: #000;
     border-radius: 50%;
     text-align: center;

     img {
       vertical-align: middle;
     }
  }
}

None SCSS version:

html, body {
  height: 100%;
  min-height: 100%;
  margin:0;
}
.wrapper {
  height: 100%;
  position: relative;
}

.wrapper .main {
     margin-top: -157px;
     margin-left: -157px;
     position: absolute;
     top: 50%;
     left: 50%;
     width: 314px;
     height: 314px;
     line-height: 314px;
     background: #000;
     border-radius: 50%;
     text-align: center;
  }

.wrapper .main img {
  vertical-align: middle;
}
<div class="wrapper">
  <div class="main"><img src="http://placehold.it/300x300" alt="">  </div>
</div>
Turnip
  • 35,836
  • 15
  • 89
  • 111