简体   繁体   中英

How do I center div horizontally and vertically within a div using flexbox?

How do I center (horizontally) and middle (vertically) a div within another div using flexbox?

Other Q/A exists , but are too specific

jsFiddle

In a flexbox, setting margin to auto will set the margin automatically for both the horizontal and vertical axis.

HTML

<div class="parent">
    <div class="child">
    </div>
</div>

CSS

html, body {width:100%;height:100%;}
.parent {
    display: flex;
    width: 100%;
    height: 100%;
    border: 5px solid red;
}

.child {
  width: 100px;
  height: 100px;
  margin: auto; /* Auto margin for both horizontal and vertical axis */
  border: 5px solid blue;
}

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