0

when I center my div, it's not centered. It seems, that his left corner is right in the middle of the screen. How can I substract the half of my width to this, that my div gets centered correctly?

In my css I write left: 50% and this is the result:

enter image description here

are there any possibilities to center this div correctly?

Question3r
  • 2,166
  • 19
  • 100
  • 200

3 Answers3

5

transform: translateX(-50%) will shift the element to the left 50% of it's own width. paired with left: 50%, it will center something on the x-axis.

Michael Coker
  • 52,626
  • 5
  • 64
  • 64
1

And to extend Michael Coker's answer:

transform: translate(-50%, -50%)

Will shift the element horizontally and vertically by half of it's width/height.

DrMcCleod
  • 3,865
  • 1
  • 15
  • 24
0

This is another logic which worked for me to align the div in center

  var divWidth = $(".center").width();
  var rowWidth = $(".row").width();
  var a = (rowWidth - divWidth) / 2;
  $(".center").css("margin-left", a);
.center {
  background-color: green;
  height: 60px;
  text-align: center;
}
<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</head>

<body>
  <div class="row">
  </div>
  <div class="center" style="width:50%">
    Hello World
  </div>
</body>

</html>
User1793
  • 47
  • 2