Darren Bachan
Darren Bachan

Reputation: 743

Unable to center :after and :before horizontally and vertically

Whenever I need to position something so it's vertical and/or horizontally I'd normally resort to flexbox, and if that's not the solution I position: absolute with top:50%; and/or left:50%; with transform: translate(-50%,-50%);. I tried this with the following code, but I did not get such results.

HTML

.plus-minus-toggle {
  cursor: pointer;
  height: 50px;
  position: relative;
  width: 50px;
  background: red;

  &:before,
  &:after{
    background: white;
    content: '';
    height: 5px;
    left: 50%;
    position: absolute;
    top: 50%;
    width: 21px;
    transform: translate(-50%,-50%);
    transition: transform 500ms ease;
  }

  &:after {
    transform-origin: center;
  }

  &.collapsed {
    &:after {
      transform: rotate(90deg);
    }

    &:before {
      transform: rotate(180deg);
    }
  }
}
    <div class="plus-minus-toggle collapsed"></div>

I am unsure about how to achieve this, I even tried wrapping the div in a parent div and applying the positioning css there, but no luck, it was the same.

Upvotes: 0

Views: 32

Answers (1)

Michael Coker
Michael Coker

Reputation: 53674

Your transforms are overriding one another and need to be combined.

$(function() {
  $('.plus-minus-toggle').on('click', function() {
    $(this).toggleClass('collapsed');
  });
});
body {
  padding: 30px;
}
.plus-minus-toggle {
  cursor: pointer;
  height: 50px;
  position: relative;
  width: 50px;
  background: red;
}
.plus-minus-toggle:before,
.plus-minus-toggle:after {
  background: white;
  content: '';
  height: 5px;
  left: 50%;
  position: absolute;
  top: 50%;
  width: 21px;
  transition: transform 500ms ease;
  transform: translate(-50%,-50%);
}
.plus-minus-toggle:after {
  transform-origin: center;
}
.plus-minus-toggle.collapsed:after {
  transform: translate(-50%, -50%) rotate(90deg);
}
.plus-minus-toggle.collapsed:before {
  transform: translate(-50%, -50%) rotate(180deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="plus-minus-toggle collapsed"></div>

Upvotes: 2

Related Questions