我对我的项目中的文章/教程列表有问题。
Scenario (图像可以是其他大小,而不是256x256,但必须是方形的,不能使用背景技巧,因为我在服务器上使用把手,图像不需要使用position: absolute)
发布于 2017-01-15 08:14:36
.tutorial {
background-color: #ccc;
position: relative;
img {
position: absolute;
display: inline-block;
width: 50px;
height: 50px;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto 0;
}
...这个
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto 0;是什么使它垂直居中。
.tutorial上的position: relative;是使img垂直居中的原因。否则它将在屏幕上垂直居中。
发布于 2017-01-15 08:22:08
您可以通过将img css从以下位置更改来修复它:
img {
position: absolute;
display: inline-block;
width: 50px;
height: 50px;
float: left;
}至:
img {
position: relative;
top: 50%;
transform: translateY(-50%);
display: inline-block;
width: 50px;
height: 50px;
float: left;
}添加position: relative、top:50%和transform:translateY(-50%)是一种非常有效的垂直居中元素的方法。
发布于 2017-01-15 08:34:59
使用JS的另一种解决方案。
<html>
<body>
<div class="tutorial" id="tutorial">
<img src="http://www.iconshock.com/img_jpg/BETA/mail_icons/jpg/256/template_icon.jpg" alt="image" id="img"/>
<div class="text">
<header>
<h1>lorem ipsum</h1>
<span>
by: who knows?
</span>
</header>
<p>
description bla bla bla bla
</p>
</div>
</div>
</body>
</html>和JS-part:
var tutorialId = document.getElementById("tutorial");
var heightTutorial = tutorialId.offsetHeight;
var imgId = document.getElementById("img");
var heightImg = imgId.offsetHeight;
var margin = (heightTutorial-heightImg);
imgId.style.marginTop=margin/2+'px';如果之后更改了教程的高度,则必须再次调用JS。
https://stackoverflow.com/questions/41656404
复制相似问题