如何以百分比垂直居中放置图像
how to position an image vertically centered with percentages
我试图在 div 中水平和垂直居中图像。我已经阅读了很多但是我找不到任何关于使用它的百分比位置的信息。这是我的 html:
<div id="two"></div>
<div id="three">
<img src="http://www.medicalpracticeinsider.com/sites/default/files/News%20Box_0.jpg" id="img" />
</div>
<div id="four"></div>
这是我的css:
*{
text-align: center;
}
#two{
height:30%;
background-color: green;
}
#three{
height:30%;
background-color: red;
}
#four{
height:30%;
background-color: blue;
}
#img{
height: 50%;
width: auto;
}
所以在水平方向上,我以 text-align
居中。我尝试使用 vertically-align: middle;
作为 #img
,但没有用。然后我尝试使用 marign
,但是,不确定要为 y 使用什么。如果我使用它,图像的左角从页面中间开始:
#three{
position: relative;
height:30%;
background-color: red;
}
#img{
height: 50%;
width: auto;
position: absolute;
height: 80%;
width: auto;
margin: 0 auto;
}
但似乎没有任何效果。我究竟做错了什么?
谢谢!
#img {
margin: 0;
display: block;
}
由于某些原因,我的 jsfiddle 没有加载您的图片,但您可以尝试这些 CSS
属性;
#img {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 40%;
height: 50%;
padding: 20px;
}
我试图在 div 中水平和垂直居中图像。我已经阅读了很多但是我找不到任何关于使用它的百分比位置的信息。这是我的 html:
<div id="two"></div>
<div id="three">
<img src="http://www.medicalpracticeinsider.com/sites/default/files/News%20Box_0.jpg" id="img" />
</div>
<div id="four"></div>
这是我的css:
*{
text-align: center;
}
#two{
height:30%;
background-color: green;
}
#three{
height:30%;
background-color: red;
}
#four{
height:30%;
background-color: blue;
}
#img{
height: 50%;
width: auto;
}
所以在水平方向上,我以 text-align
居中。我尝试使用 vertically-align: middle;
作为 #img
,但没有用。然后我尝试使用 marign
,但是,不确定要为 y 使用什么。如果我使用它,图像的左角从页面中间开始:
#three{
position: relative;
height:30%;
background-color: red;
}
#img{
height: 50%;
width: auto;
position: absolute;
height: 80%;
width: auto;
margin: 0 auto;
}
但似乎没有任何效果。我究竟做错了什么?
谢谢!
#img {
margin: 0;
display: block;
}
由于某些原因,我的 jsfiddle 没有加载您的图片,但您可以尝试这些 CSS
属性;
#img {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 40%;
height: 50%;
padding: 20px;
}