Development Tip

플로팅 요소의 부모가 붕괴되는 것을 어떻게 방지합니까?

yourdevel 2020. 9. 27. 14:09
반응형

플로팅 요소의 부모가 붕괴되는 것을 어떻게 방지합니까? [복제]


이 질문에 이미 답변이 있습니다.

<div>s 와 같은 요소는 일반적으로 내용에 맞게 커지지 만 float속성을 사용하면 CSS 초보자에게 놀라운 문제가 발생할 수 있습니다. 부동 요소에 부동 부모 요소가 없으면 부모가 축소됩니다.

예를 들면 :

<div>
  <div style="float: left;">Div 1</div>
  <div style="float: left;">Div 2</div>
</div>

이 예제에서 부모 div 는 플로팅 된 자식을 포함하도록 확장되지 않습니다height: 0 ..

이 문제를 어떻게 해결합니까?

여기에 완전한 솔루션 목록을 작성하고 싶습니다. 브라우저 간 호환성 문제를 알고있는 경우 지적 해주세요.

해결책 1

부모를 플로팅합니다.

<div style="float: left;">
  <div style="float: left;">Div 1</div>
  <div style="float: left;">Div 2</div>
</div>

장점 : 의미 론적 코드.
단점 : 부모가 항상 떠 다니는 것을 원하지 않을 수도 있습니다. 그렇게하더라도 부모의 부모를 떠 다니는 식입니까? 모든 조상 요소를 플로팅해야합니까?

해결 방법 2

부모에게 명시적인 높이를 지정하십시오.

<div style="height: 300px;">
  <div style="float: left;">Div 1</div>
  <div style="float: left;">Div 2</div>
</div>

장점 : 의미 론적 코드.
단점 : 유연하지 않음-콘텐츠가 변경되거나 브라우저 크기가 조정되면 레이아웃이 깨집니다.

해결책 3

다음과 같이 부모 요소 안에 "spacer"요소를 추가합니다.

<div>
  <div style="float: left;">Div 1</div>
  <div style="float: left;">Div 2</div>
  <div class="spacer" style="clear: both;"></div>
</div>

장점 : 코드 작성이 간단 합니다.
단점 : 의미 론적이지 않습니다. 스페이서 div는 레이아웃 해킹으로 만 존재합니다.

해결 방법 4

부모를로 설정합니다 overflow: auto.

<div style="overflow: auto;">
  <div style="float: left;">Div 1</div>
  <div style="float: left;">Div 2</div>
</div>

장점 : 추가 div가 필요하지 않습니다.
단점 : 해킹처럼 보입니다- overflow속성의 명시된 목적이 아닙니다 .

코멘트? 다른 제안?


해결책 1 :

가장 신뢰할 수 있고 눈에 띄지 않는 방법은 다음과 같습니다.

데모 : http://jsfiddle.net/SO_AMK/wXaEH/

HTML :

<div class="clearfix">
    <div style="float: left;">Div 1</div>
    <div style="float: left;">Div 2</div>
</div>​

CSS :

.clearfix::after { 
   content: " ";
   display: block; 
   height: 0; 
   clear: both;
}

약간의 CSS 타겟팅을 사용하면 부모에게 클래스를 추가 할 필요조차 없습니다 DIV.

이 솔루션은 IE8과 역 호환되므로 이전 브라우저의 실패에 대해 걱정할 필요가 없습니다.

해결책 2 :

솔루션 1에 대한 적응이 제안되었으며 다음과 같습니다.

데모 : http://jsfiddle.net/wXaEH/162/

HTML :

<div class="clearfix">
    <div style="float: left;">Div 1</div>
    <div style="float: left;">Div 2</div>
</div>​

CSS :

.clearfix::after { 
   content: " ";
   display: block; 
   height: 0; 
   clear: both;
   *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML += '<div class="ie7-clear"></div>' );
}

.ie7-clear {
    display: block;
    clear: both;
}

이 솔루션은 IE5.5와 역 호환되는 것으로 보이지만 테스트되지 않았습니다.

해결책 3 :

축소되지 않은 상태에서 일반 블록 요소 를 설정 display: inline-block;하고 width: 100%;에뮬레이션하는 것도 가능합니다 .

데모 : http://jsfiddle.net/SO_AMK/ae5ey/

CSS :

.clearfix {
    display: inline-block;
    width: 100%;
}

이 솔루션은 IE5.5와 역 호환되어야하지만 IE6에서만 테스트되었습니다.


나는 보통 overflow: auto트릭을 사용합니다 . 즉 엄격하게, 오버 플로우의 사용 목적을 말하기 아니다 있지만, 되어 좀 관련 - 충분히 쉽게 확실히 기억 할 수 있도록. float: left자체 의 의미는 이 예제 인 IMO에서 오버 플로우보다 훨씬 더 다양한 용도로 확장되었습니다.


overflow:auto부모를 입는 것보다overflow:hidden

웹 페이지에 처음으로 쓰는 CSS는 항상 다음과 같습니다.

div {
  overflow:hidden;
}

그러면 걱정할 필요가 없습니다.


이 문제는 부동 요소가 컨테이너 상자 내에있을 때 발생하며 해당 요소는 컨테이너의 높이를 부동 요소에 맞게 자동으로 조정하지 않습니다. 요소가 플로팅되면 플로트가 흐름에서 제거되므로 상위 요소에 더 이상 포함되지 않습니다. 다음 두 가지 방법을 사용하여 수정할 수 있습니다.

  • { clear: both; }
  • clearfix

무슨 일이 일어나고 있는지 이해했으면 아래 방법을 사용하여 "지우기"하십시오.

.clearfix:after {
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}

.clearfix {
    display: inline-block;
}

html[xmlns] .clearfix {
    display: block;
}

* html .clearfix {
    height: 1%;
}

데모 :)


clearfix에는 몇 가지 버전이 있으며 Nicolas GallagherThierry Koblentz 가 주요 작성자입니다.

이전 브라우저에 대한 지원을 원하는 경우 다음 clearfix를 사용하는 것이 가장 좋습니다.

.clearfix:before, .clearfix:after {
    content: "";
    display: table;
}

.clearfix:after {
    clear: both;
}

.clearfix {
    *zoom: 1;
}

SCSS에서는 다음 기술을 사용해야합니다.

%clearfix {
  &:before, &:after {
    content:" ";
    display:table;
  }

  &:after {
    clear:both;
  }

  & {
    *zoom:1;
  }
}

#clearfixedelement {
    @extend %clearfix;
}

이전 브라우저에 대한 지원에 관심이 없다면 더 짧은 버전이 있습니다.

.clearfix:after {
    content:"";
    display:table;
    clear:both;
}

Although the code isn't perfectly semantic, I think it's more straightforward to have what I call a "clearing div" at the bottom of every container with floats in it. In fact, I've included the following style rule in my reset block for every project:

.clear 
{
   clear: both;
}

If you're styling for IE6 (god help you), you might want to give this rule a 0px line-height and height as well.


The ideal solution would be to use inline-block for the columns instead of floating. I think the browser support is pretty good if you follow (a) apply inline-block only to elements that are normally inline (eg span); and (b) add -moz-inline-box for Firefox.

Check your page in FF2 as well because I had a ton of problems when nesting certain elements (surprisingly, this is the one case where IE performs much better than FF).


Strange no one has come up with a complete answer for this yet, ah well here it is.

Solution one: clear: both

Adding a block element with the style clear:both; onto it will clear the floats past that point and stop the parent of that element from collapsing. http://jsfiddle.net/TVD2X/1/

Pros: Allows you to clear an element and elements you add below will not be effected by the floated elements above and valid css.

Cons: Requires the another tag to clear the floats, bloating markup.

Note: To fall back to IE6 and for it to work on abstinent parents (i.e. the input element) you are not able to use :after.

Solution two: display: table

Adding display:table; to the parent to make it shrug off the floats and display with the correct height. http://jsfiddle.net/h9GAZ/1/

Pros: No extra markup and is a lot neater. Works in IE6+

Cons: Requires invalid css to make sure everything plays nice in IE6 and 7.

Note: The IE6 and 7 width auto is used to prevent the width being 100%+padding, which is not the case in newer browsers.

A note on the other "solutions"

These fixes work back to the lowest supported browser, over 1% usage globally (IE6), which means using :after does not cut it.

Overflow hidden does show the content but does not prevent the element from collapsing and so does not answer the question. Using an inline block can have buggy results, children having strange margins and so on, table is much better.

Setting the height does "prevent" the collapse but it is not a proper fix.

Invalid css

Invalid css never hurt anyone, in fact, it is now the norm. Using browser prefixes is just as invalid as using browser specific hacks and doesn't impact the end user what so ever.

In conclusion

I use both of the above solutions to make elements react correctly and play nicely with each other, I implore you to do the same.


I use 2 and 4 where applicable (i.e. when I know the content's height or if overflowing doesn't harm). Anywhere else, I go with solution 3. By the way, your first solution has no advantage over 3 (that I can spot) because it isn't any more semantic since it uses the same dummy element.

By the way, I wouldn't be concerned about the fourth solution being a hack. Hacks in CSS would only be harmful if their underlying behaviour is subject to reinterpretation or other change. This way, your hack wouldn't be guaranteed to work. However in this case, your hack relies on the exact behaviour that overflow: auto is meant to have. No harm in hitching a free ride.


My favourite method is using a clearfix class for parent element

.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

.clearfix {
    display: inline-block;
}

* html .clearfix {
    height: 1%;
}

.clearfix {
    display: block;
}

One of the most well known solutions is a variation of your solution number 3 that uses a pseudo element instead of a non-semantic html element.

It goes something like this...

.cf:after {
    content: " ";
    display: block;
    visibility: hidden;
    height: 0;
    clear: both;
}

You place that in your stylesheet, and all you need is to add the class 'cf' to the element containing the floats.

What I use is another variation which comes from Nicolas Gallagher.

It does the same thing, but it's shorter, looks neater, and maybe used to accomplish another thing that's pretty useful - preventing the child elements' margins from collapsing with it's parents' (but for that you do need something else - read more about it here http://nicolasgallagher.com/micro-clearfix-hack/ ).

.cf:after {
    content: " ";
    display: table;
    clear: float;
}

add this in the parent div at the bottom

 <div style="clear:both"></div>

The main problem you may find with changing overflow to auto or hidden is that everything can become scrollable with the middle mouse buttom and a user can mess up the entire site layout.


Another possible solution which I think is more semantically correct is to change the floated inner elements to be 'display: inline'. This example and what I was working on when I came across this page both use floated divs in much exactly the same way that a span would be used. Instead of using divs, switch to span, or if you are using another element which is by default 'display: block' instead of 'display: inline' then change it to be 'display: inline'. I believe this is the 100% semantically correct solution.

Solution 1, floating the parent, is essentially to change the entire document to be floated.

Solution 2, setting an explicit height, is like drawing a box and saying I want to put a picture here, i.e. use this if you are doing an img tag.

Solution 3, adding a spacer to clear float, is like adding an extra line below your content and will mess with surrounding elements too. If you use this approach you probably want to set the div to be height: 0px.

Solution 4, overflow: auto, is acknowledging that you don't know how to lay out the document and you are admitting that you don't know what to do.


I believe that best way is to set clear:both to the upcoming element.

Here's why:

1) :after selector is not supported in IE6/7 and buggy in FF3, however,
     if you care only about IE8+ and FF3.5+ clearing with :after is probably best for you...

2) overflow is supposed to do something else so this hack isn't reliable enough.

Note to author: there is nothing hacky on clearing... Clearing means to skip the floating fields. CLEAR is with us since HTML3 (who knows, maybe even longer) http://www.w3.org/MarkUp/html3/deflists.html , maybe they should chose a bit different name like page: new, but thats just a detail...

참고URL : https://stackoverflow.com/questions/218760/how-do-you-keep-parents-of-floated-elements-from-collapsing

반응형