位置:绝对不按预期工作

时间:2016-11-18 13:12:29

标签: html css sass

我有一个内部有图像的元素,我想将它居中。 我正在使用position:absolute但它无法正常工作。 这是代码:

<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;
     }
  }
}

这是图像: enter image description here

2 个答案:

答案 0 :(得分:0)

您在HTML中使用拼写错误的类名称:

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

您还需要添加height: 100%。即:

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>

答案 1 :(得分:0)

您需要将所有祖先的高度设置为100%,否则它们将折叠为零,结果将类似于您的屏幕截图。

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;
     }
  }
}

无SCSS版本:

&#13;
&#13;
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;
}
&#13;
<div class="wrapper">
  <div class="main"><img src="http://placehold.it/300x300" alt="">  </div>
</div>
&#13;
&#13;
&#13;