简体   繁体   English

如何使用div垂直居中图像?

[英]How do I center an image vertically using div?

I am currently centring an image in the horizontal using: 我目前正在使用以下命令将图像居中放置在水平位置:

.centeredImage
    {
    text-align:center;
    display:block;
    }

<!DOCTYPE html>
<html>

<head>
   <title>My Site</title>
   <link href="style.css" rel="stylesheet">

</head>

<body>

   <p class="centeredImage"><img id ="img" src="smallslide1.png"></p>

</body>
</html>

This works fine but I want to centre it vertically too. 这工作正常,但我也想垂直居中。 Not sure how to do about this. 不确定如何执行此操作。 I tired to wrap it in a separate div 我累了把它包装在一个单独的div中

.centeredVert{
    vertical-align: middle }

} 

but this didn't do anything. 但这什么也没做。 could someone give me some pointers on how to do this please? 有人可以给我一些如何做的指示吗?

You could try the absolute positioning trick on the image itself: 您可以尝试对图像本身进行绝对定位:

 .centeredImage img { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; } 
 <p class="centeredImage"> <img src="http://placehold.it/150x100"> </p> 

Try this: 尝试这个:

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

Here's the jsfiddle . 这是jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM