简体   繁体   中英

center div inside div with absolute position using flexbox

Other problem center using css, I wish center a div inside other div with absolute position, I want to get a similar result to this image:

预期

preferably using flexbox, example code:

 .abs_1 { position: absolute; background: red; height: 200px; width: 200px; top: 40px; left: 40px; } .abs_2 { position: absolute; background: blue; height: 200px; width: 200px; top: 60px; left: 250px; } .center{ display: flex; justify-content: center; align-items: center; } .center div { background: black; color: white; } 
 <div class="abs_1"> <div class="center"> <div>Hello.</div> </div> </div> <div class="abs_2"> <div class="center"> <div>World</div> </div> </div> 

I get the following:

错误

could you do this using flex css?

Here is a solution using CSS Flexbox .

CSS

#container {
    display: flex;
    justify-content: center;
    align-items: center;
}

.abs_1 {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 10px;
    background: red;
    height: 200px;
    width: 200px;
}

.abs_2 {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 10px;
    background: blue;
    height: 200px;
    width: 200px;
}

.center > div {
    background: black;
    color: white;
}

HTML

<div id="container">

    <div class="abs_1">
        <div class="center">
            <div>Hello.</div>
        </div>
    </div>

    <div class="abs_2">
        <div class="center">
            <div>World</div>
        </div>
    </div>

</div><!-- end #container -->

DEMO: http://jsfiddle.net/3ekyetc0/

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