我试图使用CSS水平居中图像.
我使用以下HTML代码在屏幕上显示我的图像:
<div id="loading" class="loading-invisible">
<img class="loading" src="logo.png">
</div>
Run Code Online (Sandbox Code Playgroud)
我正在裁剪我的图像,因为我只想显示一些图像,我正在使用以下css:
img.loading
{
position:absolute;
clip:rect(0px,681px,75px,180px);
}
Run Code Online (Sandbox Code Playgroud)
但是,一旦它被歪曲,我无法弄清楚如何使图像居中.
有人能帮忙吗?
Cyn*_*hia 119
试试这个CSS:
.center img {
display:block;
margin-left:auto;
margin-right:auto;
}
Run Code Online (Sandbox Code Playgroud)
然后添加到您的图像以使其居中:
class="center"
Run Code Online (Sandbox Code Playgroud)
Zen*_*ndy 25
像这样使用绝对位置和边距
img.loading{
position: absolute;
left: 50%;
margin-left: -(half ot the image width)px
}
Run Code Online (Sandbox Code Playgroud)
您可以使用其他方法:
方法1:
这是一种简单的方法,请text-align: center;
为您的父div 使用“ ”。
#loading {
text-align: center;
}
Run Code Online (Sandbox Code Playgroud)
<div id="loading" class="loading-invisible">
<img class="loading" src="https://dummyimage.com/200x100/000/fff.png&text=Logo">
</div>
Run Code Online (Sandbox Code Playgroud)
方法2:
请检查代码:
#loading img {
margin: 0 auto;
display: block;
float: none;
/*width: 200px; if its a large image, it need a width for align center*/
}
Run Code Online (Sandbox Code Playgroud)
<div id="loading" class="loading-invisible">
<img class="loading" src="https://dummyimage.com/200x100/000/fff.png&text=Logo">
</div>
Run Code Online (Sandbox Code Playgroud)
方法3:
使用“ display: flex;
”
#loading {
display: flex;
align-items: center;
justify-content: center;
}
Run Code Online (Sandbox Code Playgroud)
<div id="loading" class="loading-invisible">
<img class="loading" src="https://dummyimage.com/200x100/000/fff.png&text=Logo">
</div>
Run Code Online (Sandbox Code Playgroud)
方法4:
您可以使用“ position: absolute;
”,
#loading {
position: relative;
}
#loading img{
position: absolute;
top: 0;
left: 50%;
margin-right: -50%;
transform: translate(-50%, 0%);
-ms-transform: translate(-50%, 0%);
-webkit-transform: translate(-50%, 0%);
-moz-transform: translate(-50%, 0%);
-o-transform: translate(-50%, 0%);
}
Run Code Online (Sandbox Code Playgroud)
<div id="loading" class="loading-invisible">
<img class="loading" src="https://dummyimage.com/200x100/000/fff.png&text=Logo">
</div>
Run Code Online (Sandbox Code Playgroud)
希望这会帮助你。
使用margin
margin-left:auto;
margin-right:auto;
Run Code Online (Sandbox Code Playgroud)