Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

center div inside div with absolute position using flexbox

Tags:

html

css

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:

expected

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:

wrong

could you do this using flex css?

like image 648
Jose Ricardo Bustos M. Avatar asked Apr 09 '15 06:04

Jose Ricardo Bustos M.


People also ask

How do I center an absolute positioned div?

Answer: Use the CSS margin , left & right property You can align any absolutely or fixed positioned <div> element horizontally center using the CSS margin property in combination with the left and right position property.

Does Flex working with position absolute?

If you position a flex item absolutely, it no longer participates in the flex layout. This means any flex properties on the item become moot. You can remove them if you like. The box alignment properties still apply to the flex item even if it is absolutely positioned, which means using align-self will have an effect.


1 Answers

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/

like image 75
Michael Benjamin Avatar answered Sep 30 '22 05:09

Michael Benjamin