R01machin
R01machin

Reputation: 47

How to keep elements relative to a specific point in a background-image?

I got a background image of a big white square, and now I'm trying to keep a div positioned in the corner of that square, but when I resize the page, that div doesn't follow that corner. I suppose that occurs because of the background-size: cover;, since that condition keeps zooming in/out when resized.

I also would like to keep that square in the proportion of the white square.

background-image and div in normal size: background-image and div in normal size

resized background-image and div: enter image description here

I'm already using position: absolute; and relative.

I've been trying to use only flexible values (vh, vw, %)

  .bg {
  background-image: url("https://i.pinimg.com/originals/3b/6a/ed/3b6aede10e30d93886268de33d67039e.jpg");
  height: 100vh;
  width: 100vw;
  background-size: cover;
  position: relative;
}

.el {
  width: 5%;
  height: 5%;
  position: absolute;
  left: 13.8%;
  top: 28.5%;
  background: orange;
}

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding:
<div class="bg">
  <div class="el"></div>
</div>

Upvotes: 1

Views: 242

Answers (1)

Ere M&#228;nnist&#246;
Ere M&#228;nnist&#246;

Reputation: 964

One problem is that the image you are using as the background is not only a "black square" since it has white paddings.

If you want everything to align in the box, you either need to:

  1. calculate how much the image has paddings before the box (I don't recommend doing).
  2. crop the image a bit, removing the white padding.

Here are the calculations after getting rid of the white paddings, and leaving just the borders. You can mess around with the width, height, left, and top for more desired results.

.bg {
  background-image: url("bg.jpg");
  height: 50vh;
  width: 50vh;
  position: relative;
  margin: 25vh 25vw;
  background-repeat: no-repeat;
  background-position: center;
  background-attachment: initial;
  background-size: cover;
}

/* Calculating the "borders" of the image out of the width and height, in this case 1.7% * 2 */
.el {
  width: calc(100% - 3.4%);
  height: calc(100% - 3.4%);
  position: absolute;
  left: 1.7%;
  top: 1.7%;
  background: orange;
}

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

My image has a little bit of white at the bottom, since I cropped the picture a bit badly. Your element width & height ratio should always be 1:1, if you want the .el to work.

Also, if the purpose is just to make a box with black borders, you might want to do it with just HTML and CSS, since it's definitely more complex using background images

Here are the results after cropping the paddings and applying the new code

Upvotes: 2

Related Questions