首页 > 解决方案 > 更改背景宽度时,它也会更改容器位置

问题描述

我正在做的是,我有两个背景图像,每个图像都有一个相应的红色框。红框是一个内部引导容器,具有绝对位置。第一个红色框在右侧,第二个红色框在左侧。

直到没有问题为止。

现在我必须更改背景图像的宽度,因为我必须在第一张图像上留出左侧空间,在第二张图像上留出右侧空间。

但是如果你注意到我是否给了空间,那么它就会改变容器的位置。我不想改变容器的位置。

没有空间的时候

在此处输入图像描述

请检查下图。有空间的时候

在此处输入图像描述

.bodywrapper {
  margin-top: 40px;
}

.container {
  position: relative;
  height: 100%;
}

.bannerBg {
  height: 350px;
  background-size: cover;
  background-repeat: no-repeat;
  margin-bottom: 30px;
  width: 92%;
}

.wrapperOne {
  background-image: url('https://mdbootstrap.com/img/Photos/Slides/img%20(45).jpg');
}

.wrapperTwo {
  background-image: url('https://mdbootstrap.com/img/Photos/Slides/img%20(46).jpg');
}

.box {
  background-color: red;
  height: 220px;
  width: 320px;
  position: absolute;
  bottom: 0
}

.rightside {
  right: 0;
}

.leftside {
  left: 0;
}
<div class="bodywrapper">

  <div class="wrapperOne bannerBg ml-auto">
    <div class="container">
      <div class="box rightside"></div>
    </div>
  </div>

  <div class="wrapperTwo bannerBg mr-auto">
    <div class="container">
      <div class="box leftside"></div>
    </div>
  </div>

</div>

v>

我需要知道这是否可能。

标签: htmlcssbootstrap-4

解决方案


您的代码不会产生像您拍摄的 2 张图像那样的结果,因此我对其进行了一些调整。

.bodywrapper {
  margin-top: 40px;
  text-align: right;
}

.container {
  position: relative;
  height: 100%;
  width: 70%;
  display: inline-block;
}

.bannerBg {
  height: 350px;
  background-size: cover;
  background-repeat: no-repeat;
  margin-bottom: 30px;
  width: 100%;
}

.wrapperOne {
  background-image: url('https://mdbootstrap.com/img/Photos/Slides/img%20(45).jpg');
  text-align: center;
  background-size: 70% 100%;
  background-position: right;
  display: inline-block;
}

.wrapperTwo {
  background-image: url('https://mdbootstrap.com/img/Photos/Slides/img%20(46).jpg');
  text-align: center;
  background-size: 70% 100%;
  background-position: left;
  display: inline-block;
}

.box {
  background-color: red;
  height: 220px;
  width: 320px;
  position: absolute;
  bottom: 0
}

.rightside {
  right: 0;
}

.leftside {
  left: 0;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="menu.css">
</head>
<body>
  <div class="bodywrapper">

    <div class="wrapperOne bannerBg ml-auto">
      <div class="container">
        <div class="box rightside"></div>
      </div>
    </div>

    <div class="wrapperTwo bannerBg mr-auto">
      <div class="container">
        <div class="box leftside"></div>
      </div>
    </div>

  </div>
</body>
</html>

主要部分是将以下代码添加到 2wrapper

text-align: center;
background-size: 70% 100%;
background-position: right; //in wrapper one and  left in wrapper two
display: inline-block;

这个想法是减少包装器图像的宽度,而不是包装器本身,因此您的容器位置不会改变。


推荐阅读