如何将图像水平和垂直居中在div中

时间:2017-11-21 16:39:48

标签: html css html5 css3

我想在水平和垂直方向上居中我的图像,但我可以水平居中,同时我想要这个响应,任何人都可以帮助我吗?在这里输入代码

.video{
width: 100%;
height: 500px;
background-color: peru;
position: absolute;
}

.moldura{
	display: block;
	width: 50px;
	margin-right: auto;
	margin-left: auto;
	margin-top: auto;
	margin-bottom: auto;
	border: 1px solid black;
}

.moldura img{
	width: 50px;
}
<!DOCTYPE html>
<html>
<head>
	<title>TESTE</title>
<link rel="stylesheet" type="text/css" href="estilo.css">
</head>
<body>

	<div class="video"> 
		<div class="moldura">
			<img src="https://lh4.ggpht.com/SKQHLsT8xsNpXeL5si4bBqSNqdy8Qbvzk15J3qWTp55AnnkbNO6-vBJhIBTQxyq16YE=w300">
		</div>

	</div>
	
</body>
</html>

3 个答案:

答案 0 :(得分:2)

您是否尝试过使用弹性盒?

编辑:根据评论,不,我不知道使用“对齐项目”,运作良好,我已经相应编辑了片段! :)

.video{
display:flex;
justify-content: center;
align-items: center;
flex-direction:column;
height:250px;
background-color: peru;
}

.moldura{

}

.moldura img{
 height:50px;
 border:1px solid black;
}
<!DOCTYPE html>
<html>
<head>
	<title>TESTE</title>
<link rel="stylesheet" type="text/css" href="estilo.css">
</head>
<body>

	<div class="video"> 
		<div class="moldura">
			<img src="https://lh4.ggpht.com/SKQHLsT8xsNpXeL5si4bBqSNqdy8Qbvzk15J3qWTp55AnnkbNO6-vBJhIBTQxyq16YE=w300">
		</div>

	</div>
	
</body>
</html>

答案 1 :(得分:0)

你有:

.video{
width: 100%;
height: 500px;
background-color: peru;
position: absolute;
}

.moldura{
  display: block;
  width: 50px;
  border: 1px solid black;

  /* Here is the important code*/
  position: relative;
  top: 50%;
  left: 50%;
  transform:translate(-50%, -50%);
}

.moldura img{
	width: 50px;
}
<!DOCTYPE html>
<html>
<head>
	<title>TESTE</title>
<link rel="stylesheet" type="text/css" href="estilo.css">
</head>
<body>

	<div class="video"> 
		<div class="moldura">
			<img src="https://lh4.ggpht.com/SKQHLsT8xsNpXeL5si4bBqSNqdy8Qbvzk15J3qWTp55AnnkbNO6-vBJhIBTQxyq16YE=w300">
		</div>

	</div>
	
</body>
</html>

答案 2 :(得分:0)

添加了行高css属性。

&#13;
&#13;
.video{
width: 100%;
height: 500px;
background-color: peru;
position: absolute;
}

.moldura{
	display: block;
	width: 50px;
	margin:0 auto;
    line-height:500px;
    height:100%;
}

.moldura img{
	width: 50px;
    vertical-align:middle;
}
&#13;
<!DOCTYPE html>
<html>
<head>
	<title>TESTE</title>
<link rel="stylesheet" type="text/css" href="estilo.css">
</head>
<body>

	<div class="video"> 
		<div class="moldura">
			<img src="https://lh4.ggpht.com/SKQHLsT8xsNpXeL5si4bBqSNqdy8Qbvzk15J3qWTp55AnnkbNO6-vBJhIBTQxyq16YE=w300">
		</div>

	</div>
	
</body>
</html>
&#13;
&#13;
&#13;