float does not work in a flex container

耗尽温柔 提交于 2020-01-26 09:44:09

问题


I want to position text (foo link) in right of the footer element.

I need footer display to remain flex.

But when I set it to flex, float:right for span doesn't work anymore.

<footer style="display: flex;">
     <span style="text-align: right;float: right;">
        <a>foo link</a>
     </span>
</footer>

https://jsfiddle.net/dhsgvxdx/


回答1:


The float property is ignored in a flex container.

From the flexbox specification:

3. Flex Containers: the flex and inline-flex display values

A flex container establishes a new flex formatting context for its contents. This is the same as establishing a block formatting context, except that flex layout is used instead of block layout.

For example, floats do not intrude into the flex container, and the flex container’s margins do not collapse with the margins of its contents.

float and clear do not create floating or clearance of flex item, and do not take it out-of-flow.

Instead, just use flex properties:

footer {
    display: flex;
    justify-content: flex-end;
}
<footer>
    <span>
       <a>foo link</a>
    </span>
</footer>

If you have more items in the footer, and need other alignment options, then here are two guides:

  • In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?
  • How does flex-wrap work with align-self, align-items and align-content?



回答2:


It works if you add margin-left: auto; like I did here in the jsfiddle: https://jsfiddle.net/dhsgvxdx/3/

<body>
    <footer style="display: flex;">
        <span style="text-align: right;float: right; margin-left: auto;">
            <a>foo link</a>
        </span>
    </footer>
</body>



回答3:


If this footer is only to contain a right-aligned item, you can simply apply justify-content: flex-end to the flex container. This way, you do not have to add any styles to its children.

footer {
  display: flex;
  justify-content: flex-end;
}

Codepen example



来源:https://stackoverflow.com/questions/39194630/float-does-not-work-in-a-flex-container

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!