[英]How can I perfectly center my image?
因此,我的网站上有一张图片,我想使其完美居中。 我尝试了很多事情,但是都没有成功。
body{ background-color: black; } img { position: absolute; margin-top: 10%; text-align: center; height: 40%; z-index: -5 }
<img src="images/astronaut.png">
使图像水平居中的最简单方法是:
img {
display: block;
margin-right: auto;
margin-left: auto;
}
像这样?
body{ background-color: black; } img { position: absolute; margin-top: 10%; text-align: center; height: 40%; z-index: -5; left: 50%; top:50%; transform: translate(-50%, -50%); }
<img src="images/astronaut.png">
居中代码是left
, top
,尤其是transform
请查看以下链接以获取进一步的帮助,希望对您有所帮助。
https://www.w3.org/Style/Examples/007/center
https://css-tricks.com/snippets/css/absolute-center-vertical-horizontal-an-image/
html { width: 100%; height: 100%; background:url(http://tse4.mm.bing.net/th?id=OIP.IX1fAIIUJ82DtdfgR2tSnADhEs&w=207&h=276&c=8&qlt=90&o=4&dpr=2&pid=1.7) center center no-repeat; }
如果您的位置未设置或设置为相对,则将左右边距设置为自动将使图像在其父对象中水平居中。
因此,您可以使用:
img {
margin-top: 10%;
margin-left: auto;
margin-right: auto;
text-align: center;
height: 40%;
z-index: -5
}
如果您需要将位置设置为绝对位置,则可以使用CSS3的视口大小来使图像居中。 这会将图像放置在页面的确切中心; 因此,例如,如果您想将图像居中放置在侧边栏中,请不要使用此方法。 您需要为图片设置宽度,然后使用“ left”属性将其对齐。 看起来像这样:
img {
position: absolute;
margin-top: 10%;
text-align: center;
height: 40%;
z-index: -5
width: 500px;
left: calc( 50vw - 250px );
}
视口始终为100vw宽,因此将left属性设置为50vw-图片宽度的1/2会将其在页面上居中。
您也可以使用jQuery类似地计算元素的正确对齐方式和位置。
您可以将图像放入div中,使其宽度和高度占屏幕的100%。
然后添加text-align:center; 将其水平居中。
然后将线条高度设置为100%,然后添加vertical-align:middle; 图像的垂直居中位置。
body{ background-color: black; } .CenterImage img { height: 40%; z-index: -5; vertical-align: middle; } .CenterImage{ width:100vw; height:100vh; line-height: 100vh; text-align:center; }
<div class="CenterImage"><img src="images/astronaut.png"></div>
body{ background-color: black; } img { position: absolute; text-align: center; height: 40%; top: 50%; left: 50%; z-index: -5 }
<img src="images/astronaut.png">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.