I want to make a div
stick on the top of the screen without any influence to other elements, and its child element in the center.
.parent {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
position: absolute;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">text</div>_x000D_
</div>
_x000D_
When I add the position: absolute
line, justify-content: center
becomes invalid. Do they conflict with each other and, what's the solution?
EDIT
Thanks guys it's the problem of parent width. But I'm in React Native, so I can't set width: 100%
. Tried flex: 1
and align-self: stretch
, both not working. I ended up using Dimensions to get the full width of the window and it worked.
EDIT
As of newer version of React Native (I'm with 0.49), it accepts width: 100%
.
This question is related to
css
react-native
flexbox
In my case, the issue was that I had another element in the center of the div with a conflicting z-index.
.wrapper {_x000D_
color: white;_x000D_
width: 320px;_x000D_
position: relative;_x000D_
border: 1px dashed gray;_x000D_
height: 40px_x000D_
}_x000D_
_x000D_
.parent {_x000D_
position: absolute;_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
top: 20px;_x000D_
left: 0;_x000D_
right: 0;_x000D_
/* This z-index override is needed to display on top of the other_x000D_
div. Or, just swap the order of the HTML tags. */_x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
.child {_x000D_
background: green;_x000D_
}_x000D_
_x000D_
.conflicting {_x000D_
position: absolute;_x000D_
left: 120px;_x000D_
height: 40px;_x000D_
background: red;_x000D_
margin: 0 auto;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="parent">_x000D_
<div class="child">_x000D_
Centered_x000D_
</div>_x000D_
</div>_x000D_
<div class="conflicting">_x000D_
Conflicting_x000D_
</div>_x000D_
</div>
_x000D_
you have forgotten width of parent
.parent {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
position: absolute;_x000D_
width:100%_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">text</div>_x000D_
</div>
_x000D_
You have to give width:100%
to parent to center
the text.
.parent {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
position: absolute;_x000D_
width:100%_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">text</div>_x000D_
</div>
_x000D_
If you also need to centre align vertically, give height:100%
and align-itens: center
.parent {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
width:100%;
height: 100%;
}
Source: Stackoverflow.com