相对于背景定位图像

时间:2019-03-17 13:12:58

标签: html css bootstrap-4

我希望图像的放置位置始终使其中心位于蓝色背景的底部。 它看起来应该像这样: enter image description here

我可以使用top:37v;但调整窗口高度的大小不会使其相对于背景的位置保持不变。

.background{
    background-image: url("https://i.imgur.com/5Y5F5fF.png");
    background-repeat: no-repeat;
    background-size: cover;
    background-position: 0 100%;
    height: 50vh;
}
header img{
    position: relative;
    height: 100px;
    /*!*top: 37vh;*! Don't want to use this as resizing will effect its position relative to background*/
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<header>
        <div class="container-fluid d-flex justify-content-center background">
            <img src="https://i.imgur.com/3dzn4KM.png" alt="phone">
        </div>

    </header>

2 个答案:

答案 0 :(得分:1)

将这2行添加到样式中:

header img{
     position: relative;
     height: 100px;
     top:50%;
     margin-top:-50px;
 }

这应该有帮助。

答案 1 :(得分:1)

您可以像这样使用position: relativeabsolute的组合:

.background {
  background-image: url("https://i.imgur.com/5Y5F5fF.png");
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 0 100%;
  height: 50vh;
  position: relative;
}

header img {
  position: absolute;
  height: 100px;
  bottom: -50px;
  /*!*top: 37vh;*! Don't want to use this as resizing will effect its position relative to background*/
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<header>
  <div class="container-fluid d-flex justify-content-center background">
    <img src="https://i.imgur.com/3dzn4KM.png" alt="phone">
  </div>

</header>