Div与纵横比 - 如何将图像置于其中心?

时间:2016-07-15 14:21:21

标签: html css css3

我有1:1的比例div,并希望将图像垂直和水平居中。我怎么能这样做?

.main {
  width: 200px;
}
.aspect-ratio-1-1 {
  width:100%;
  padding-top:100%;
  position: relative;
}

.aspect-ratio-1-1 div {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color:orange;
  }
}
<div class="main">
  <div class="aspect-ratio-1-1">
    <div>
      <img src="http://placehold.it/150x100">
     </div>
   </div>
</div>

2 个答案:

答案 0 :(得分:7)

您可以使用几乎适用于所有浏览器的技术,方法是将边距设置为auto,将position设置为absolute,将top / right / bottom / left设置为零:

img {
  position:absolute;
  margin:auto;
  top:0;
  right:0;
  bottom:0;
  left:0;
}

.main {
  width: 200px;
}
.aspect-ratio-1-1 {
  width: 100%;
  padding-top: 100%;
  position: relative;
}
.aspect-ratio-1-1 div {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: orange;
}
img {
  position:absolute;
  margin:auto;
  top:0;
  right:0;
  bottom:0;
  left:0;
}
<div class="main">
  <div class="aspect-ratio-1-1">
    <div>
      <img src="http://placehold.it/150x100">
    </div>
  </div>
</div>

另一种技术使用CSS3转换:

img {
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  position: absolute;
}

.main {
  width: 200px;
}
.aspect-ratio-1-1 {
  width: 100%;
  padding-top: 100%;
  position: relative;
}
.aspect-ratio-1-1 div {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: orange;
}
img {
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  position: absolute;
}
<div class="main">
  <div class="aspect-ratio-1-1">
    <div>
      <img src="http://placehold.it/150x100">
    </div>
  </div>
</div>

答案 1 :(得分:4)

我们不要忘记 flexbox

&#13;
&#13;
<asp:Button CssClass="btn btn-warning" ID="btnModalSuccess" runat="server" Text="Close" ToolTip="Click to close this screen." />
&#13;
.main {
  width: 200px;
}
.aspect-ratio-1-1 {
  width:100%;
  padding-top:100%;
  position: relative;
}

.aspect-ratio-1-1 div {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color:orange;
  display:flex;
  justify-content:center;
  align-items:center;
 
}
&#13;
&#13;
&#13;