在居中的svg上堆叠图像

时间:2017-07-11 13:35:06

标签: javascript html css svg

此刻我正在使用svg和flexbox,我想将图像堆叠在一个居中的svg之上。

图像应位于svg的中心,我也想完成图像与svg按比例缩放。

是否可以使用flexbox完成此操作,还是应该考虑其他内容?

HTML:

<div class="container">
  <div class="main">
    <div class="spotlight">
      <img src="https://www.stadiumgoods.com/media/catalog/product/cache/1/base/1000x600/9df78eab33525d08d6e5fb8d27136e95/3/6/365054_02_1.png" alt="sneaker" class="sneaker" />
      <svg id="circle-bg" viewBox="0 0 100 100">
        <circle fill="#F8F5F5" cx="50" cy="50" r="50"></circle>
      </svg>
    </div>
  </div>
</div>

CSS:

body {
  background-color: #EBEBED;
  margin: 0;
}

.main {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.spotlight {
  width: 50vw;
  max-height: 75vh;
}

.sneaker {
  position: absolute;
  width: 50%;
}

#circle-bg {
  height: 75vh;
}

的jsfiddle:https://jsfiddle.net/hvgom8o3/

预期结果:

Expected result

2 个答案:

答案 0 :(得分:1)

您需要将.spotlight设为弹性框:

Fiddle

&#13;
&#13;
body {
  background-color: #EBEBED;
  margin: 0;
}

.main {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.spotlight {
  width: 50vw;
  max-height: 75vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.sneaker {
  position: absolute;
  width: 50%;
}

#circle-bg {
  height: 75vh;
}
&#13;
<div class="container">
  <div class="main">
    <div class="spotlight">
      <img src="https://www.stadiumgoods.com/media/catalog/product/cache/1/base/1000x600/9df78eab33525d08d6e5fb8d27136e95/3/6/365054_02_1.png" alt="sneaker" class="sneaker" />
      <svg id="circle-bg" viewBox="0 0 100 100">
        <circle fill="#F8F5F5" cx="50" cy="50" r="50"></circle>
      </svg>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

借助Gerard和Stackoverflow上的其他帖子的灵感,我找到了一个流畅的解决方案。

将自动边距应用于绝对定位图像,同时将顶部,右侧,底部和左侧设置为零,这样做了。

HTML:

<div class="container">
  <div class="main">
    <div class="spotlight">
      <img src="https://www.stadiumgoods.com/media/catalog/product/cache/1/base/1000x600/9df78eab33525d08d6e5fb8d27136e95/3/6/365054_02_1.png" alt="sneaker" class="sneaker" />
      <svg id="circle-bg" viewBox="0 0 100 100">
        <circle fill="#F8F5F5" cx="50" cy="50" r="50"></circle>
      </svg>
    </div>
  </div>
</div>

CSS:

body {
  background-color: #EBEBED;
  margin: 0;
}

.main {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.spotlight {
  width: 50vw;
  max-height: 75vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.sneaker {
  position: absolute;
  width: 70%;
  margin: auto;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
}

小提琴:http://jsfiddle.net/146t817h/1/