Monday, March 16, 2015

Centering a div inside a div - Responsive Design

When I was creating a simple html theme, I wanted to create a basic page that will be good for both desktops and mobiles. So, I created this simple div structure to put my contents in the center of the screen.



Let me show you how I achieved it.

STEP 1:  Creating main DIV and content DIV

Create one div and mark it class as "main" like below

<div class="main"> 
   <div  class="content">
        MY WEBSITE CONTENT 
   </div>
</div>

STEP 2: Applying Styles

For thing I would do in this step is to add a colored border, so that we can differentiate the divs.
  .main {
   border: 1px solid red;
 }

.content {
  border: 1px solid green; 

}

Now, make the "main" div to be 100% of the device width and a minimum width of 300px (This is just my preference. You can have any minimum width.)
And also, "content" div to be 50% of the "main" div width and a minimum width of 280px( Again this is my preference)

This would like 
.main {
  width: 100%;
   min-width: 300px;
   border: 1px solid red;
 }
.content {
  width:50%;
  min-width:280px;
  border: 1px solid green; 

}


The key part is to apply width margin property to "content" div.

Apply margin as
margin: 0 auto;
What it says is zero margin on top and bottom. Auto margin on left and right.

Finally the css would look like,
.main {
    width:100%;   
    min-width:300px;
    border:1px solid red;   
}

.body {
    max-width: 50%;
    min-width : 270px;
    margin:0 auto;
    border:1px solid green;
}

And the result is this..


I have created a demo fiddle here

No comments:

Post a Comment