如何将div放在背景图像中间,其大小包含?

时间:2018-02-20 00:22:32

标签: javascript css

我有一个背景图片,其大小设置为:

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 div始终保持在背景图像的中心?使用CSS和/或JavaScript?

或者其他一些方法可以使图像响应并且始终在中心设置div?

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

2 个答案:

答案 0 :(得分:0)

我认为这是不可能的,无法检索由contain等修饰符调整大小的背景图像的大小。

响应式图像解决方案

Codepen

所以我决定尝试用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();

答案 1 :(得分:-2)

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>