Reputation: 18097
Here is jsfiddle: http://jsfiddle.net/techsin/1o5zzcgh/
I want to center two absolutely positioned divs inside each other without using jquery. Right now I'm using top:0, and bottom 0 but when height is defined this doesn't work.
* {
margin: 0;
padding: 0;
}
html, body {
position: relative;
height: 100%;
width: 100%;
}
.in, .out {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.in {
background-color: red;
height: 50%;
}
.out {
background-color: blue;
}
Upvotes: 0
Views: 41
Reputation: 7248
You need to add margin:auto; to the absolute positioned divs and then apply height:50%; and width:50%; to .in div.
* {
margin: 0;
padding: 0;
}
html, body {
position: relative;
height: 100%;
width: 100%;
}
.in, .out {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin:auto;
}
.in {
background-color: red;
height: 50%;
width:50%;
}
.out {
background-color: blue;
}
JSFIDDLE: http://jsfiddle.net/a_incarnati/1o5zzcgh/1/
You can also set a height, but then you need to remember that since the container it's 100%, it will not be a square.
Upvotes: 1
Reputation: 1114
You can use this little hack:
HTML:
<div class="out">
<div class="in">
</div>
</div>
CSS:
.in, .out {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.in {
background-color: red;
height: 50%;
left: 50%;
top: 50%;
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
.out {
background-color: blue;
}
By using left / top along with translate minus values you can center as you wanted.
HTH.
Upvotes: 2
Reputation: 2551
Are you referring to something like this?
* {
margin: 0;
padding: 0;
}
html, body {
position: relative;
height: 100%;
width: 100%;
}
.in, .out {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.in {
width: 50%;
height:50%;
top: 20%;
left: 20%;
background-color: red;
}
.out {
background-color: blue;
}
Upvotes: 0