redAce
redAce

Reputation: 1798

How should i center exactly a div both vertically and horizontally?

I'm big newbie in CSS, but i tried different things, but I just can't get my div to be centered vertically.

Parent :

#ModalScroll{
    position:absolute;
    top:0;
    left:0;
    z-index:1001; 
    height:1px;
    width:1px;
    overflow:hidden;
    display:none;
    font-size:100%;
    text-align:left;
}

Child :

.ModalDialog{
    border:1px solid #3C4749;
    background-color:#FFF;
    margin:0 auto 0 auto;
    display:none;
    font-size: 12px;
    box-sizing: border-box; 
    width: 280px;
    height: 160px; 
    position: absolute;
    left: 50%;
    top: 50%;
    margin: -80px 0 0 -140px;
}

I don't know if a solution in jQuery should be better, but I would prefer one in CSS.

Upvotes: 1

Views: 102

Answers (3)

Random
Random

Reputation: 3236

Have you used firebug in order to be sure that your css is fully used ? (maybe an other CSS overloads some attributes of your item...)

position:absolute; /*it can be fixed too*/
left:0; right:0;
top:0; bottom:0;
margin:auto;

should do the trick (as said in Center a DIV horizontally and vertically) maybe try to add "!important" to each attribute...

EDIT : here is the css with "!important" mark :

position:absolute !important;
left:0 !important;
right:0 !important;
top:0 !important;
bottom:0 !important;
margin:auto !important;

Upvotes: 1

Prasanga
Prasanga

Reputation: 1038

Here is code for your question,

HTML code :


<div class="maindiv">
    <p class="hdiv">JSFIDDLE V</p>
</div>
<br>
<div class="maindivh">
    <p class="hdih">JSFIDDLE H</p>
</div>

CSS code :

.maindiv {   position:relative; border:1px solid #cfcfcf; height:50px; width:200px; }

.hdiv {width:200px; text-align:center; height:50px;}

.maindivh { position:relative; border:1px solid #cfcfcf; height:150px; width:200px; }

.hdih { vertical-align:middle; display:table-cell; line-height:150px; text-align:center; width:200px; }

demo

Upvotes: 1

Aru
Aru

Reputation: 1870

try this:

HTML

<div class="divContent">
    content goes here
</div>

Css

.divContent {
    width: 200px;
    height: 300px;
    border: 1px solid red;
    position:absolute;
    left:0;
    right:0;
    top:0;
    bottom:0;
    margin:auto;
}

Upvotes: 1

Related Questions