html - How to center one of two flex items in a flex container? -
i want box 2 in center of #box-cntnr
i'm using align-self
property. i'd open other approaches on accomplishing this. jsfiddle.
html
<div id="box-cntnr"> <div class="box" id="b1">box 1</div> <div class="box" id="b2">box 2</div> </div>
css
.box { width: 100px; height: 100px; background-color: lightblue; margin: 10px; } #box-cntnr { display: flex; } #b1 { align-self: center; }
assuming want box #2 centered both vertically , horizontally in flex container, first thing need give container height.
in code, flex item center horizontally because container has no height specified, resolves content height , vertical space limited.
html (no changes)
css
html, body { height: 100%; } body { margin: 0; } #box-cntnr { display: flex; position: relative; height: 100%; background-color: yellow; } .box { width: 100px; height: 100px; background-color: lightblue; margin: 10px; } #b2 { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }
flex alignment properties such justify-content
, align-items
, align-self
, auto
margins work distributing free space in flex container. if box #2 flex item in container, use these properties perfect centering.
however, box #2 has sibling (box #1), these properties cannot used centering box #1 occupying space, , throw off calculation. in other words, flex alignment properties center box #2 in remaining space.
the easiest way around absolute positioning. can apply position: relative
container , position: absolute
box #2. removes box #2 document flow , enables align freely within entire space of parent.
Comments
Post a Comment