My current project involves two stacked divs, each measuring 100px by 100px. The bottom div includes a black border on top, as shown in this example.
<div id="top"></div>
<div id="bottom"></div>
div {
width: 100px;
height: 100px;
}
#top {
background: tomato;
}
#bottom {
border-top: 1px solid black; background: gold;
}
I am seeking a method to use the top div to conceal the border on the bottom one without removing it entirely.
Usually, I would achieve this by setting position: relative
and z-index
on both divs, ensuring that div#one has a higher z-index
than div#two. Then add margin-bottom: -1px
to div#one, similar to this approach:
div {
width: 100px;
height: 100px;
position: relative;
}
#top {
z-index: 9999;
margin-bottom: -1px;
background: tomato;
}
#bottom {
z-index: 1;
border-top: 1px solid black;
background: gold;
}
However, through experimentation, I discovered that floating the top div (while still keeping the negative bottom margin) and clearing the bottom one provided a simpler solution. By doing this, there's no need for position: relative
or z-index to conceal the border, as long as the negative bottom margin is added to the top div. Refer to this alternative example:
div {
width: 100px;
height: 100px;
}
#top {
float: left;
margin-bottom: -1px;
background: tomato;
}
#bottom {
clear: both;
border-top: 1px solid black;
background: gold;
}
This method works effectively, with less code required. Is this a reliable, cross-browser way to stack elements on top of each other, or should I stick to the traditional approach using z-index as I usually do?