user782220
user782220

Reputation: 11187

Centering div horizontally and vertically

I a blue div set to display: inline-block; so that it shrink wraps to its content. I am trying to center the blue div in the middle of the red div.

<a href="www.google.com">hi</a>
<div class="dim">
    <div class="test">
        <div> test </div>
        <div> 2nd </div>        
    </div>
</div>​

.dim {
    height:100%;
    width:100%;
    position:fixed;
    left:0;
    top:0;
    z-index:1 !important;
    background-color:red;
    opacity: 0.5;
}

.test {
    border: solid;
    display: inline-block;
    background-color:blue;
}

Jsfiddle link to code

Upvotes: 0

Views: 193

Answers (1)

harrypujols
harrypujols

Reputation: 2284

I tried this in your fiddle. It worked.

.test {
    border: solid;
    display: inline-block;
    background-color:blue;
    position: fixed;
    margin-top: 50%;
    margin-left:50%
}

It will break once you resize the div. If you don't set a size to your div, the only way it will stay in the center without an stablished size is with JavaScript.

But, you don't have to look too hard to find better answers.

Upvotes: 3

Related Questions