繁体   English   中英

如何将div居中包含大小的背景图像中间?

[英]How to center a div in the middle of a background image with size contain?

我有一个背景图片,其大小设置为包含以下内容:

background: url('https://cdn.sstatic.net/Sites/stackoverflow/img/404.svg') no-repeat center center;
background-size: contain;

我有一个div,我一直希望它位于背景图片的中心

<div class="bg">
  <div class="center"></div>
</div>

有没有办法.center.center div保持在背景图像的中心? 使用CSS和/或JavaScript?

还是通过其他方式使图像具有响应性并始终使div位于中心?

代码笔示例https://codepen.io/brunolm/pen/GQxRVP

我认为这是不可能的,没有办法在contain诸如修饰符之类的修饰符的背景图像上检索尺寸。

响应式图像解决方案

码笔

因此,我决定尝试将图像放置在一个position: absolute并且我要居中的div也以绝对位置定位。

容器

我可以通过设置样式来居中

align-items: center;
bottom: 0;
display: flex;
height: 100%;
justify-content: center;
left: 0;
position: relative;
right: 0;
top: 0;

图片

我可以使用以下方法使图像响应

max-height: 100%;
max-width: 100%;

我可以通过禁用选择使其表现得像背景

user-select: none;

我可以居中

bottom: 0;
margin: auto;
position: absolute;
top: 0;

居中div

我可以居中

position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;

计算大小

并计算以图像为中心的div大小

function doResize() {
  const img = document.getElementById('img');
  const center = document.getElementById('center');

  // img is responsive and width/height is available
  center.style.width = `${img.width * 0.5}px`;
  center.style.height = `${img.height * 0.65}px`;

  console.log(img.width, 'x', img.height);
}

// recalculate whenever the window size changes
window.addEventListener('resize', doResize);

// calculate initial size
doResize();

display: flex; align-items: center; margin: 0 auto; 是这里的关键字。 要使div像bg img一样高,请使用以下示例: https : //codepen.io/phng/pen/PWEJGO 然后可以使用position:absolute; 否定第二个div上的填充。

 * { box-sizing: border-box; margin: 0; padding: 0; } .ufo { background: url('https://cdn.sstatic.net/Sites/stackoverflow/img/404.svg') no-repeat center; display: flex; align-items: center; border: 1px solid #000; width: 500px; height: 500px; } .ufo div { width: 150px; height: 150px; background-color: steelblue; margin: 0 auto; } 
 <div class="ufo"> <div> </div> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM