Home > Software engineering >  How to show parent background image inside of a nested button?
How to show parent background image inside of a nested button?

Time:10-31

My structure is as follows:

.root-div {
  display: inline-block;
  background-image: url('...');
  background-size: cover;
  width: 100vw;
  height: 100vh;
  position: relative;
}

.auth {
  margin: 3rem auto;
  width: 95%;
  max-width: 25rem;
  border-radius: 6px;
  background-color: darkcyan;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
  padding: 1rem;
  text-align: center;
}

.btn {
  /* should be showing part of the root-div's background image */
}
<div className="root-div">
  <div className="auth">
    <button className="btn">Submit</button>
  </div>
</div>

I would like for my button to show through to the root-div's background image. Setting it to transparent of course doesn't work because auth's styles are then shown. What would be some approaches to achieve this effect? Thank you.

CodePudding user response:

Try this trick by using the same background image into the button and set as fixed background it will look like the background button is transparent and showing the background, you can play around with the background-size property of the button to match background positions and sizes

.btn {
    background-image: url('https://unsplash.it/640/425');
    background-size:cover;
    background-attachment: fixed;
    padding: 20px;
}

screenshot

CodePudding user response:

If you want to just make the button have a background image, you should collapse the HTML structure and just add the classes to the button element.

.root-div {
  display: inline-block;
  background-image: url('https://placekitten.com/200/70');
  background-size: cover;
  width: 100vw;
  height: 100vh;
  position: relative;
}

.auth {
  margin: 3rem auto;
  width: 95%;
  max-width: 25rem;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
  padding: 1rem;
}

.btn:hover {
    cursor: pointer;
}
<button >Submit</button>

CodePudding user response:

If the parent has background image then the inside elements should be transparent

.root-div {
  display: inline-block;
  background-image: url('...');
  background-size: cover;
  width: 100vw;
  height: 100vh;
  position: relative;
}

.auth {
  margin: 3rem auto;
  width: 95%;
  max-width: 25rem;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
  padding: 1rem;
  text-align: center;

background-color: transparent
}

.btn {
     background-color: transparent
}

  • Related