Problem:
The issue you are having is that by default, your child elements align themselves to the top left of their parent element, and not in the center as you are expecting. In order to position your child element in the center (horizontally), you could use the css of:
margin: 0 auto;
which will place it horizontally in the middle.
Vertically aligning is slightly more difficult, as it involves ensuring it to be the correct from both top and bottom of your parent, so you could use:
top: 25%;
However, this should really only be used if your child is positioned in accordance to your parent div, and so we need to include position:absolute;
into our child element.
However, if we do this, then it would be more beneficial to set it using both left
and top
properties, like so (in our child element):
position: absolute;
left:25%;
top:25%;
So, using this we come to our first solution:
Solution 1: Using positioning
By using absolute
positioning, and making your parent have relative
positioning, this will solve your problem.
#first {
width: 100px;
height: 100px;
background: red;
position: relative;
}
#first #second {
position: absolute;
width: 50%;
height: 50%;
background: green;
left: 25%;
top: 25%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>BOX-EXAMPLE</title>
</head>
<body>
<div id="first">
<div id="second"></div>
</div>
</body>
</html>
Solution 2: Pseudo Effects
You may also want to use pseudo effects to reduce your markup (makes the page load slightly faster), and so we could use pseudo effects to a great beneficial degree (since we only use a single element instead of two):
This is shown below:
#first {
width: 100px;
height: 100px;
background: red;
position: relative;
}
#first:after {
content:"";
width: 50%;
height: 50%;
background: green;
position: absolute;
left:25%;
top:25%;
}
<div id="first"></div>