0

I'm trying and failing to generate a simple cross (made with vertical and horizontal components) within a parent element (box).

.box {
  width: 50vmin;
  height: 50vmin;
  background-color: blue;
  margin: 0 auto;
}

.vertical {
  position: absolute;
  width: 10%;
  height: 80%;
  top: calc((100% - 80%) / 2);
  left: calc((100% - 10%) / 2);
  background-color: black;
}

.horizontal {
  position: absolute;
  width: 80%;
  height: 10%;
  top: calc((100% - 10%) / 2);
  left: calc((100% - 80%) / 2);
  background-color: black;
}
<div class="box">
  <div class="vertical"></div>
  <div class="horizontal"></div>
</div>
  

The output that I expected was a black cross centred within the blue a box. Can someone please tell me where I've gone wrong?

Thanks for your help!

ajrlewis
  • 2,968
  • 3
  • 33
  • 67

1 Answers1

5

Making the parent .box relative, you keep .vertical and .horizontal relative to .box and not the window (or other parent element with relative).

Try this:

.box {
 width: 50vmin;
 height: 50vmin;
 background-color: blue;
 margin: 0 auto;
 position: relative; /* CHANGED HERE */
}

.box {
  width: 50vmin;
  height: 50vmin;
  background-color: blue;
  margin: 0 auto;
  position: relative;
}

.vertical {
  position: absolute;
  width: 10%;
  height: 80%;
  top: calc((100% - 80%) / 2);
  left: calc((100% - 10%) / 2);
  background-color: black;
}

.horizontal {
  position: absolute;
  width: 80%;
  height: 10%;
  top: calc((100% - 10%) / 2);
  left: calc((100% - 80%) / 2);
  background-color: black;
}
<div class="box">
  <div class="vertical"></div>
  <div class="horizontal"></div>
</div>
Biotox
  • 1,563
  • 10
  • 15