user1760110
user1760110

Reputation: 2336

How to center a div inside outer div horizontally, vertically and responsively

I am working on this demo. How can I center the second div #two both horizontally and vertically? Can we have a set up to take care of the positions even in responsive mode or browser size changing?

I followed a trick from CSS-Trick but it didn't work for me:

<div id="wrap">
    <div id="two"></div>
</div>

body {
    padding:25px;
}
#wrap {
    height:380px;
    width:60px;
    border:1px solid;

}
#two {
    height:300px;
    width:6px;
    background:#b2b2b2;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -160px;
    margin-top: -30px;
}

Upvotes: 0

Views: 60

Answers (2)

LOTUSMS
LOTUSMS

Reputation: 10240

When it comes to responsiveness you must stay away from absolute positioning as much as possible and use percentages instead of fixed widths.

The rest is just good ol css

body {
   padding:25px;
}
#wrap {
   height:380px;
   width:100%;
   max-width:600px;
   border:1px solid;
   margin:0 auto;
   padding:25px;
 }
 #two {
   height:300px;
   width:100%;
   max-width:400px;
   background:#b2b2b2;
   margin: 0px auto
 }

Notice how the boxes actually decrease in size as you shrink the window

FIDDLE

Upvotes: 0

misterManSam
misterManSam

Reputation: 24692

This is what you need!

#wrap has been given position: relative;. This means any child elements of #wrap with position: absolute; will be positioned relative to it and not body.

The negative margins of #two need to be exactly half of the width and height of that div.

In regards to automatic sizing, this cannot be achieved with CSS alone using this method.

Have a fiddle - Fiddle Link!

HTML

<div id="wrap">
    <div id="two"></div>
</div>

CSS

#wrap {
    position: relative;
    width:500px;
    height:500px;
    border: solid 1px #CCC;
    overflow: hidden;

}

#two {
    height:300px;
    width:300px;
    background:#b2b2b2;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -150px;
    margin-top: -150px;
}

Upvotes: 1

Related Questions