1

I have a simple JSFiddle I am basically trying to overlay one div over another. I can do this easily in a traditional div (see purple) but when I try the same thing with a button it doesn't work.

<button>
  <div class="background">&nbsp;</div>
  <div class="label">This is the label</div>
</button>

.background{
  background-color: green;
  height: 100%;
}
.label{
  position: relative;
  top: -100%;
}

How do I position a div relatively inside a button?

Jackie
  • 21,969
  • 32
  • 147
  • 289

2 Answers2

3

You could use position: absolute; on the child .label and position: relative; on the parent button.

Like this:

button {
  position: relative;
}

.label{
  position: absolute;
  top: 0;
}
  • I still have the question of absolute positioning and mobile though. I will try it out but I remember absolute positioning having issues in older browsers. – Jackie Dec 28 '19 at 16:31
  • It doesn't look that bad - https://caniuse.com/#search=position%3A%20absolute –  Dec 28 '19 at 16:33
  • It has been a while but I will see if it works like I need to on the browsers I use (especially Safari because that seems to lag). – Jackie Dec 28 '19 at 16:43
  • So If you can fix this I will give you the check back (https://jsfiddle.net/9u4nw1fv/19/) notice it doesn't maintain a width unless declared. – Jackie Dec 28 '19 at 16:47
  • The reason it doesn't maintain a width is that the background doesn't adjust it's width after the sibling –  Dec 28 '19 at 16:53
  • I got it to work by switching and fiddling with the z-index. The problem is the top element sets the size for the whole button. The issue I have here is this makes me need a z-index on all items I expect to show up. I tried just putting it on the label but it doesn't work https://jsfiddle.net/9u4nw1fv/30/ – Jackie Dec 28 '19 at 16:57
  • @Jackie See this: https://stackoverflow.com/a/48226415/9572013. I don't know if it works with buttons, but it makes an element the size of it's sibling –  Dec 28 '19 at 16:59
0

You can do it like this:

button{
    position: relative; /* will make all absolute elements inside it relative to itself */
}
.label{
    position: absolute;
    top: -100%;
}
GROVER.
  • 4,071
  • 2
  • 19
  • 66