0

I have a div (child) that is positioned absolute within a parent container (positioned relative). I want this child div to be centered vertically and horizontally within its container both on desktop and mobile, however the child div moves positioning depending on the size of the window. How do apply consistent centered positioning across devices?

HTML

<div class="container">
  <div class="child">
  </div>
  <div class="child-2">
  </div>
</div>

CSS

.container {
  width: 300px;
  height: 300px;
  border: solid 1px blue;
  position: relative;
}

.child {
  position: absolute;
  width: 50px;
  height: 50px;
  background-color: red;
  position: absolute;
  right: 50%;
  left: 50%;
  top: 50%;
  border-radius: 100%;
}

.child-2 {
  border-bottom: solid 1px blue;
  width: 300px;
  height: 150px;
}

JSFiddle for example - http://jsfiddle.net/hfndkywe/8/

FakeEmpire
  • 668
  • 1
  • 14
  • 35

1 Answers1

1

it is always safe to use transform to make the element center, see the following code

 .child {
  position: absolute;
  width: 50px;
  height: 50px;
  background-color: red;
  left: 50%;
  top: 50%;
  border-radius: 100%;
  transform: translate(-50%,-50%);
}

when you use left and right positioning, it is always pushing div from the sides not from the center, so in order to make exactly at center transform is the easy fix.

Jismon Thomas
  • 783
  • 1
  • 6
  • 22