0

I have an element inside of a parent inside of a grandparent. I am attempting to place the element halfway down the parent element using position: absolute and top: 50%. However, the element appears 50% of the way down the grandparent element instead. Why is this?

Here is my Sass:

#cons
  background: #242424
  border-right: 1px solid white
  width: $leftwidth
  margin: 0
  padding: 0
  height: calc(100% - 81px)
  overflow-y: scroll
#cons > li
  width: 100%
  height: 50px
  background-color: #212121
  border-bottom: 1px solid white
  display: block
#cons > li img
  width: 40px
  height: 40px
  border-radius: 40px
  margin: 0
  margin-top: 25px
  transform: translateY(-50%)
  display: inline
#cons > li span
  display: inline
  height: 5px
  position: absolute
  top: 50%

Here is my Pug:

ul(id='cons')
      li
        img(src='download.jpg')
        span Hello World

The element that I am trying to centre is the span element saying Hello World

Graham
  • 7,431
  • 18
  • 59
  • 84
tom894
  • 459
  • 1
  • 3
  • 14

1 Answers1

1

The positioning context of a positioned element (absolute/relative/fixed/sticky - all except static) is the closest parent with position other than static (the default). Set position: relative on the li:

#cons > li
  position: relative
  width: 100%
  height: 50px
  background-color: #212121
  border-bottom: 1px solid white
  display: block
Ori Drori
  • 183,571
  • 29
  • 224
  • 209