Home > Software engineering >  How to keep image and text relative to each other, regardless of screen size.(reponsive)
How to keep image and text relative to each other, regardless of screen size.(reponsive)

Time:10-28

I placed a text over an image, but when I increase the screen size the image won't follow, its just stuck at the same place, contrary to the text that responds to the screen-size and moves to the center.

HTML


<div >
  <img src="assets/script.png" alt="">
  <div >
    <h1>About Us</h1>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad cum architecto eius molestiae dolore est id vero voluptatem
      repellat voluptas quo beatae nulla ex soluta deleniti impedit maxime, enim omnis?</p>
  </div>
</div>

CSS

.section2{

  max-height: 20rem;
  padding-top: 20px;
  position: relative;
}

.section2 img{
  padding: 20px
}

.abtus {
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  width: 60%;
  font-size: 1rem;
  text-align: center;
  padding-top: 6rem;

}

CodePudding user response:

I think img tag must have width: 100% to follow the parent element size.

img {
    width: 100%;
    padding: 20px;
}

CodePudding user response:

If you want to position an absolute element on a picture then you should:

1- put the image and the element in one container.

.container {
    height: fit-content;
    width: fit-content;
    position: relative;
}

2- the image width should be 100% so it can resize according to its parent's width.

3- Use the container to resize the image, don't resize the image itself.

.section2{
    max-height: fit-content;
    width: 100vw;
    position: relative;
    border: 1px solid red;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .container {

    height: fit-content;
    width: fit-content;
    position: relative;
    border: 1px solid blue;
    display: flex;
    justify-content: center;
    align-items: center;

  }
  
  .section2 img {
    height: auto;
    width: 80%;
    border: 1px solid red;
  }
  
  .abtus {
    position: absolute;
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
    width: 60%;
    font-size: 1rem;
    text-align: center;
    padding-top: 6rem;
  }
 <div >
    <div >
      <img src="https://cdn.pixabay.com/photo/2016/01/08/15/18/lizard-1128263_960_720.jpg" alt="">
      <div >
        <h1>About Us</h1>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad cum architecto eius molestiae dolore est id vero voluptatem
          repellat voluptas quo beatae nulla ex soluta deleniti impedit maxime, enim omnis?</p>
      </div>
    </div>
  </div>

  • Related