简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM