如何在这种情况下垂直居中img

时间:2017-03-17 04:23:07

标签: html css

如何在这种情况下垂直居中img?

http://imgur.com/a/MWOND

我一直在尝试按照以下链接中的代码进行操作,但也许是因为divi builder和当前布局设置不起作用的方式。

https://designpieces.com/2012/12/vertical-centering-image-in-a-div/

4 个答案:

答案 0 :(得分:1)

您可以将父级设置为position: relative,然后使用left: 50%; top: 50%; transform: translate(-50%,-50%);绝对定位图像,将其置于中心位置。



body {
  margin: 0;
}
div {
  width: 100vw;
  height: 100vh;
  position: relative;
  background: #aaa;
}
img {
  max-width: 100px; /* this isn't necessary */
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%,-50%);
}

<div>
  <img src="https://futurism.com/wp-content/uploads/2015/11/neildegrassetyson.jpg">
</div>
&#13;
&#13;
&#13;

您还可以将flexbox与justify-content: center; align-items: center;一起使用,将图像置于中间

&#13;
&#13;
body {
  margin: 0;
}
div {
  width: 100vw;
  height: 100vh;
  background: #eee;
  display: flex;
  justify-content: center;
  align-items: center;
}
img {
  max-width: 100px; /* this isn't necessary */
}
&#13;
<div>
  <img src="https://futurism.com/wp-content/uploads/2015/11/neildegrassetyson.jpg">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用flex属性

的解决方案

#content{
display:flex;
flex-direction:row;
background:#eee;}

#block2_2
{width:100%;
height:300px;
border:1px solid #111;
}

#block2_3
{width:100%;
height:300px;
border:1px solid #000;
}
#block2
{width:50%;
height:600px;

}
#block3
{width:50%;
height:600px;
border:1px solid #000;
display:flex;
align-content:center;
align-items:center;
justify-content:center;

}
#img{
width:200px;
height:200px;
border:1px solid #000;
overflow:hidden;
}
<div id="content">

<div id="block2">
<div id="block2_2"></div>
<div id="block2_3"></div>
</div>
<div id="block3">
<div id="img"><img src="http://lorempixel.com/400/200/"></div>

</div>
</div>

答案 2 :(得分:0)

看看这个小提琴:https://jsfiddle.net/NayanaDas/gs7nxnms/。添加此css:

#container {
    height: 200px;
    line-height: 200px;
   display:-moz-box; 
-moz-box-pack:center; 
-moz-box-align:center; 

display:-webkit-box; 
-webkit-box-pack:center; 
-webkit-box-align:center; 

display:box; 
box-pack:center; 
box-align:center;
}

#container img {
    vertical-align: middle;
}

答案 3 :(得分:0)

body {
  margin: 0;
}
div {
 align-items: center;
    background: #ccc;
    display: block;
    float: left;
    height: 300px;
    justify-content: center;
    position: relative;
    width: 100%;
}
img {
  max-width: 100px; /* this isn't necessary */
   position:absolute;
   top:0;
   bottom:0;
   left:0;
   right:0;
   margin:auto;
}
<div>
  <img src="https://futurism.com/wp-content/uploads/2015/11/neildegrassetyson.jpg">
</div>