<分区>
标签 css
<分区>
我正在尝试将图像居中并在 CSS 中固定位置。我试过的代码
<style>
.bgimg {
top: 50%;
left: 50%;
position: fixed;
opacity:0.09;
marging: auto;
}
</style>
引用https://www.w3schools.com/code/tryit.asp?filename=FJZQPD9BZUBG
最佳答案
对于可变宽度/高度的内容,您需要使用带有转换的百分比偏移,如下所示:
.bgimg {
top: 50%;
left: 50%;
position: fixed;
opacity:0.09;
transform: translate(-50%, -50%);
}
或者,如果您知道宽度和高度,则可以避免使用转换并将所有位置设置为 0
并与 margin: auto;
配对:
.bgimg {
width: 400px;
height: 400px;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
您可以在下面看到这两种方法的实际效果!
.bgimg {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
opacity: .5;
}
/* you need to set the width and height on this one, otherwise it stretches it to fill */
.center-something-without-transform {
width: 50px;
height: 50px;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
background-color: blue;
}
<img class="bgimg" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/200/287.jpg" />
<div class="centered-without-transform"></div>
关于css - 如何在固定位置的情况下将图像设置在中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46474228/