-1

#first {
  position: relative;
  width: 20%;
  height: 20%;
  border-radius: 50%;
  background-color: #94b8b8;
}
#second {
  position: absolute;
  width: 15%;
  height: 15%;
  border-radius: 50%;
  background-color: blue;
}
<html>

<body>
  <div id="first">
    <div id="second">
    </div>
  </div>
</body>

</html>

How to get it i want the second div in the exact center of the first div but it is not even visible. how achieve this without using left, top attributes. note:i wants align it only using css but not using tag.

ketan
  • 19,129
  • 42
  • 60
  • 98

3 Answers3

0

There are several possibilities to do what you want:

.outer {
  background: lightblue;
  width: 300px;
  height: 100px;
}
.inner {
  background: black;
  width: 100px;
  height: 50px;
  color: white;
}
<div class="outer" align="center">
  <div class="inner">
    Deprecated (use css)
  </div>
</div>
<br>
<div class="outer">
  <div class="inner" style="position: relative; left: 50%; margin-left: -50px;">
    :)
  </div>
</div>
<br>
<div class="outer" style="position: relative">
  <div class="inner" style="position: absolute; left: 50%; margin-left: -50px;">
    :)
  </div>
</div>
<br>
<div class="outer">
  <div class="inner" style="margin: 0 auto;">
  </div>
</div>

Another solution

.outer {
  width: 100%;
  text-align: center;
}

.inner {
  display: inline-block;
}
Artem Lopatiy
  • 948
  • 5
  • 15
0

To center absolutely positioned div with known width, you can use this:

.inner1 {
  left: 0;
  right: 0;
  margin: auto;
}

Or, if you need to center it both horizontally and vertically:

.inner2 {
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}

If width of inner is unknown - use css3 transforms:

.inner3 {
  left: 50%;
  transform: translateX(-50%);
  top: 0;

}

Ant for vertical centering also:

.inner4 {
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);

}

Fiddle demo: https://jsfiddle.net/4qxpc0ua/

Julia
  • 1,301
  • 1
  • 14
  • 29
0

calculate the top and left position and apply it for the second div.

   #first {
     position: relative;
     width: 200px;
     height: 200px;
     border-radius: 50%;
     background-color: #94b8b8;
   }
   #second {
     position: absolute;
     width: 15%;
     height: 15%;
     left:42.5%; //50% - (15% / 2)
     top:42.5%; //50% - (15% / 2)
     border-radius: 50%;
     background-color: blue;
   }

DEMO

Suresh Ponnukalai
  • 13,820
  • 5
  • 34
  • 54