skip to Main Content

I have a sensorvalue that needs updating ever some secs and I indicate the type of the sensor with an image.
My code roughly looks like this:

<div class="sensor">
    <img src="images/ssensor.png" 
         class="img-fluid img-max">
    <div class="sensortext">
        sensorvalue
    </div>
</div>

with css:

.sensor {
  position: relative;
  width: 100%;
}

.sensortext {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-30%, -80%);
}

this works fine until I make the window bigger / smaller – then the images resize bigger / smaller but the text stays. How can I transform it along?

2

Answers


  1. Try with this CSS:

    .sensor {
    position: relative;
    width: 100%;
    }
    
    .sensortext {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    }
    
    .img-max {
    max-width: 100%;
    height: auto;
    display: block;
    margin: 0 auto;
    transform: translate(-50%, -50%) scale(1);
    }
    

    The issue is that the text stays fixed in its position when the image is resized. To solve this, you can use the CSS "transform" property for the image element as well, so that its size changes proportionally to the image resize. You can use the "translate" value for the X and Y axis displacement and the "scale" value for the image resize. This will dynamically center the text relative to the image.

    Login or Signup to reply.
  2. You can use vmin as suggested by Rene in the comments.
    However, I would use it within a clamp function, this allows you to specify a
    min, ideal and max value. You can play with these values and find what works best for you!

    Furthermore, for simple overlays, I would just use grid instead of absolute position, since you don’t have to mess with the stacking context this way.

    .container {
      display: grid;
      place-items: center;
    }
    
    .container * {
      grid-area: 1 / 1;
    }
    
    .container-text {
      color: white;
      font-size: clamp(3rem, 10vmin, 6rem);
    }
    <div class="container">
      <img src="https://loremflickr.com/640/360" alt="placeholder">
      <div class="container-text">
        Overlay text
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search