将背景图像准确地放置在屏幕的中间位置



我正在寻找定位图像的最佳方法,使其正好挂在图像的中点上。

我环顾四周,发现了关于在div中定位的各种东西,但不是在整个屏幕中。

我尝试过position: absolute;background-position和其他css样式。

使用百分比无法正常工作,因为调整屏幕大小时,图像会向左/向右移动,并且不会固定在垂直轴上。

.background {
position: absolute;
top: 10px;
left: 50%;
width: 50%;
height: 250px;
background-image: url('https://www.google.com/logos/doodles/2020/december-holidays-days-2-30-6753651837108830.3-law.gif');
background-position: 0 0;
background-repeat: no-repeat;
background-size: cover;
}
<html>
<body>
<div class="background">
</div>
</body>
</html>

您使用了background,因此无法获得所需内容。

所以在我做的时候:

CSS&HTML:

.background {
width: 50%;
margin-right: 25%;
float: right;
height: 500px;
text-align: center;;
}
img{
width: 100%
}
<html>
<body>
<div class="background">
<img src="https://www.google.com/logos/doodles/2020/december-holidays-days-2-30-6753651837108830.3-law.gif">
</div>
</body>
</html>

通用解决方案

margin: 0 auto;是在屏幕或其父屏幕中居中div的最常见和最简单的解决方案。margin: 0 auto;是将上下边距设置为零、将左右边距设置为自动的简写。

.background {
margin: 0 auto;
width: 50%;
height: 250px;
background-image: url('https://www.google.com/logos/doodles/2020/december-holidays-days-2-30-6753651837108830.3-law.gif');
background-position: 0 0;
background-repeat: no-repeat;
background-size: cover;
}
<body>
<div class="background">
</div>
</body>

固定解决方案(不推荐(

如果你想要居中的div已经固定了和高度,你可以用定位来管理它。

#center {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -100px;
width: 200px;
height: 100px;
background-color: #111314;
}
<div id='center'></div>

另一个解决方案

Flexbox是一种很好的方法。它是响应的,但您必须将它的父级设置为具有display属性的flexjustify-content: center;将水平居中,align-items: center;将垂直居中。

html,body {
height: 100%;
}
.parent {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.center {
background-color: #112341;
width: 100px;
height: 100px;
}
<div class="parent">
<div class="center"></div>
</div>

最终对我起作用的是将背景元素设置为position:fixed,然后将宽度设置为200%。无论屏幕的宽度是多少,这总是将图像保持在屏幕的中间

.background {
position: fixed;
background-position-x: center;
background-position-y: center;
background-repeat: no-repeat;
background-size: contain;
background-image: url('https://marketing.dcassetcdn.com/blog/30-Famous-Triangle-Logos/google-drive-logo.jpeg');
height: 75%;
width: 200%;
}
<html>
<body>
<div class="background">
</div>
</body>
</html>

最新更新