programing

플렉스 아이템을 오른쪽으로 띄우기

kingscode 2021. 1. 18. 08:10
반응형

플렉스 아이템을 오른쪽으로 띄우기


나는

<div class="parent">
    <div class="child" style="float:right"> Ignore parent? </div>
    <div> another child </div>
</div>

부모는

.parent {
    display: flex;
}

첫 번째 아이의 경우 항목을 오른쪽으로 간단히 띄우고 싶습니다.

그리고 내 다른 div는 부모가 설정 한 플렉스 규칙을 따릅니다.

이것이 가능합니까?

그렇지 않은 경우 float: right언더 플렉스를 어떻게 수행 합니까?


플렉스 컨테이너float 내부에서 사용할 수 없으며 그 이유는 여기에서 볼 수 있듯이 float 속성이 플렉스 레벨 상자에 적용되지 않기 때문입니다 .Fiddle

따라서 child요소를 요소 오른쪽에 배치 parent하려면 사용할 수 margin-left: auto있지만 이제 child요소는 div여기에서 볼 수 있듯이 다른 요소도 오른쪽으로 밀게 됩니다 Fiddle.

이제 할 수있는 것은 요소의 순서를 변경하고 요소에 설정 order: 2하여 child두 번째 div에 영향을주지 않도록하는 것입니다.

.parent {
  display: flex;
}
.child {
  margin-left: auto;
  order: 2;
}
<div class="parent">
  <div class="child">Ignore parent?</div>
  <div>another child</div>
</div>


수레가 필요하지 않습니다. 사실, float는 flexbox에서 무시 되기 때문에 쓸모가 없습니다 .

CSS 포지셔닝도 필요하지 않습니다.

몇 가지 플렉스 방법을 사용할 수 있습니다. auto여백다른 답변 에서 언급되었습니다 .

다른 두 가지 옵션이 있습니다.

  • 사용 justify-content: space-betweenorder속성.
  • justify-content: space-betweendiv의 순서를 사용 하고 뒤집습니다.

.parent {
    display: flex;
    justify-content: space-between;
}

.parent:first-of-type > div:last-child { order: -1; }

p { background-color: #ddd;}
<p>Method 1: Use <code>justify-content: space-between</code> and <code>order-1</code></p>

<div class="parent">
    <div class="child" style="float:right"> Ignore parent? </div>
    <div>another child </div>
</div>

<hr>

<p>Method 2: Use <code>justify-content: space-between</code> and reverse the order of 
             divs in the mark-up</p>

<div class="parent">
    <div>another child </div>
    <div class="child" style="float:right"> Ignore parent? </div>
</div>

참조 URL : https://stackoverflow.com/questions/36182635/making-a-flex-item-float-right

반응형