Home > Back-end >  Layering Text Without White Background
Layering Text Without White Background

Time:04-03

I am trying to complete the Odin Project's "Sign-Up Form" but I am having trouble with layering the text over the image.

enter image description here

If I use position:absolute; the text does not respect the container's width.

If I use position:relative; I get a white background under the text.

I am in dire need of guidance.

Thank you.

<div >    
    <h1>Sign up now!</h1>
    <img src="1.jpg" alt="">    
</div>

<style>
    img { 
        width: 100%;
        z-index: -1;
    }

    h1 {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        position: relative;

    }
</style>

CodePudding user response:

You're almost there with position: absolute. The last piece is you need to set position: relative to .container-one which is the container for both image and text.

<div >
  <h1>Sign up now!</h1>
  <img src="https://images.unsplash.com/photo-1612151855475-877969f4a6cc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aGQlMjBpbWFnZXxlbnwwfHwwfHw=&w=1000&q=80" alt="">
</div>

<style>
  .container-one {
    position: relative;
    width: 50%;
  }
  
  img {
    width: 100%;
    z-index: -1;
  }
  
  h1 {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    position: absolute;
  }
</style>

You can check this doc

Another solution for your case could be background-image

<div >
  <h1>Sign up now!</h1>
</div>

<style>
  .container-one {
    position: relative;
    width: 50%;
    height: 100vh;
    background-size: contain;
    background-repeat: no-repeat;
    background-image: url('https://images.unsplash.com/photo-1612151855475-877969f4a6cc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aGQlMjBpbWFnZXxlbnwwfHwwfHw=&w=1000&q=80');
  }
  
  h1 {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    position: absolute;
  }
</style>

CodePudding user response:

Try it like this:

.container-one{
  position: relative;  
}

img { 
  width: 100%;  
}

h1 {
  top: 30%;
  left: 0;
  width: 100%;
  position: absolute;
  z-index: 55;
  text-align: center;
}

Basically you make the h1 to be absolutely positioned. And sets a higher z-index so that it will appear above the image element. And also, set the container-one to be relatively positioned so that your absolutely positioned h1 will use it to calculate it's positioning.

You can control the position using the top. And to center align the text, use the text-align property.

Here's the fiddle

CodePudding user response:

The best practice is that you use the image as a background-image for the div containing the text. you'll have an easy manipulation over everything.

  • Related