Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep a transformed element behind another element?

Tags:

css

.container {
  width: 100px;
  height: 100px;
  font-size: 100px;
}

.background {
  color: red;
  width: 100%;
  height: 100%;
  margin-bottom: -100%;
  transform: rotate(90deg);
}

.foreground {
  color: blue;
  width: 100%;
  height: 100%;
}
<div class="container">
  <div class="background">B</div>
  <div class="foreground">F</div>
</div>

This example is also in here: https://jsfiddle.net/jasajona/vmzfgkcb/ How to keep transformed background div behind foreground? Found several examples but they seems not to work in this situation.

like image 790
Jonas Avatar asked Oct 15 '25 20:10

Jonas


2 Answers

Just add a position: relativeto both layers, and then sort them using z-index (if position is not set, it's considered static and static does not account for z-indexes)

.container {
  width: 100px;
  height: 100px;
  font-size: 100px;
}

.background {
  color: red;
  width: 100%;
  height: 100%;
  margin-bottom: -100%;
  transform: rotate(90deg);
  position: relative;
  z-index: 1;
}

.foreground {
  color: blue;
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 2;
}
<div class="container">
  <div class="background">B</div>
  <div class="foreground">F</div>
</div>
like image 161
somethinghere Avatar answered Oct 17 '25 14:10

somethinghere


The problem is that transforming an element creates a new "stacking context", which supersedes the source order that would otherwise determine which element is on "top".

There are several ways of dealing with this problem, but my favorite way of getting around this strangeness of CSS's z-index calculations is to add an opacity property to your foreground element:

.container{
  width: 100px;
  height: 100px;
  font-size: 100px;
}

.background {
  color: red;
  width: 100%;
  height: 100%;
  margin-bottom: -100%;
  transform: rotate(90deg);
} 

.foreground {
  color: blue;
  width: 100%;
  height: 100%;
  opacity: 0.999;
}
<div class="container">
  <div class="background">B</div>
  <div class="foreground">F</div>
</div>

Here are two resources about z-index stacking context:

  • https://philipwalton.com/articles/what-no-one-told-you-about-z-index/

  • https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

like image 42
nvioli Avatar answered Oct 17 '25 12:10

nvioli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!