div
다른 요소에 영향을주지 않고 화면 상단에 막대 를 만들고 중앙에 자식 요소 를 만들고 싶습니다 .
.parent {
display: flex;
justify-content: center;
position: absolute;
}
<div class="parent">
<div class="child">text</div>
</div>
position: absolute
라인을 추가하면 justify-content: center
무효가됩니다. 그들은 서로 충돌하고 있으며 해결책은 무엇입니까?
편집하다
고마워요 부모 너비의 문제입니다. 하지만 저는 React Native에 있으므로 설정할 수 없습니다 width: 100%
. 시도 flex: 1
및 align-self: stretch
, 둘 다 작동하지 않습니다. 결국 Dimensions 를 사용 하여 창의 전체 너비를 얻었고 작동했습니다.
편집하다
최신 버전의 React Native (0.49 사용)에서는 width: 100%
.
답변
아니요, 절대 위치 지정은 플렉스 컨테이너와 충돌하지 않습니다. 요소를 플렉스 컨테이너로 만드는 것은 내부 레이아웃 모델, 즉 콘텐츠가 배치되는 방식에만 영향을줍니다. 위치 지정은 요소 자체에 영향을 미치며 흐름 레이아웃에 대한 외부 역할을 변경할 수 있습니다.
즉
-
를 사용하여 요소에 절대 위치 지정을 추가하면
display: inline-flex
블록 수준 (예display: flex
:)이되지만 여전히 플렉스 형식화 컨텍스트를 생성합니다. -
를 사용하여 요소에 절대 위치 지정을 추가
display: flex
하면 채우기 사용 가능한 것 대신 축소-맞춤 알고리즘 (일반적인 인라인 수준 컨테이너)을 사용하여 크기가 조정됩니다.
즉, 절대 위치 지정은 플렉스 자식과 충돌 합니다.
out-of-flow이므로 플렉스 컨테이너의 절대 위치 자식은 플렉스 레이아웃에 참여하지 않습니다.
답변
부모의 너비를 잊었습니다
.parent {
display: flex;
justify-content: center;
position: absolute;
width:100%
}
<div class="parent">
<div class="child">text</div>
</div>
답변
당신은 주어야합니다 width:100%
center
텍스트 를 부모 합니다.
.parent {
display: flex;
justify-content: center;
position: absolute;
width:100%
}
<div class="parent">
<div class="child">text</div>
</div>
수직으로 가운데 정렬해야하는 경우 height:100%
및align-itens: center
.parent {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
width:100%;
height: 100%;
}
답변
제 경우 문제는 충돌하는 Z- 색인이있는 div 중앙에 다른 요소가 있다는 것입니다.
.wrapper {
color: white;
width: 320px;
position: relative;
border: 1px dashed gray;
height: 40px
}
.parent {
position: absolute;
display: flex;
justify-content: center;
top: 20px;
left: 0;
right: 0;
/* This z-index override is needed to display on top of the other
div. Or, just swap the order of the HTML tags. */
z-index: 1;
}
.child {
background: green;
}
.conflicting {
position: absolute;
left: 120px;
height: 40px;
background: red;
margin: 0 auto;
}
<div class="wrapper">
<div class="parent">
<div class="child">
Centered
</div>
</div>
<div class="conflicting">
Conflicting
</div>
</div>
답변
