Floating elements within a div, floats outside of div. Why?

前端 未结 10 953
灰色年华
灰色年华 2020-11-22 05:10

Say you have a div, give it a definite width and put elements in it, in my case an img and another div.

The idea

相关标签:
10条回答
  • 2020-11-22 05:25

    There's nothing missing. Float was designed for the case where you want an image (for example) to sit beside several paragraphs of text, so the text flows around the image. That wouldn't happen if the text "stretched" the container. Your first paragraph would end, and then your next paragraph would begin under the image (possibly several hundred pixels below).

    And that's why you're getting the result you are.

    0 讨论(0)
  • 2020-11-22 05:27

    Thank you LSerni you solved it for me.

    To achieve this :

    +-----------------------------------------+
    | +-------+                     +-------+ |
    | | Text1 |                     | Text1 | |
    | +-------+                     +-------+ |
    |+----------------------------------------+
    

    You have to do this :

    <div style="overflow:auto">
        <div style="display:inline-block;float:left"> Text1 </div>
        <div style="display:inline-block;float:right"> Text2 </div>
    </div>
    
    0 讨论(0)
  • 2020-11-22 05:28

    Here's more modern approach:

    .parent {display: flow-root;} 
    

    No more clearfixes.

    p.s. Using overflow: hidden; hides the box-shadow so...

    0 讨论(0)
  • 2020-11-22 05:28

    In some cases, i.e. when (if) you're just using float to have elements flow on the same "line", you might use

    display: inline-block;
    

    instead of

    float: left;
    

    Otherwise, using a clear element at the end works, even if it may go against the grain to need an element to do what should be CSS work.

    0 讨论(0)
  • 2020-11-22 05:32

    The easiest is to put overflow:hidden on the parent div and don't specify a height:

    #parent { overflow: hidden }
    

    Another way is to also float the parent div:

    #parent { float: left; width: 100% }
    

    Another way uses a clear element:

    <div class="parent">
       <img class="floated_child" src="..." />
       <span class="clear"></span>
    </div>
    

    CSS

    span.clear { clear: left; display: block; }
    
    0 讨论(0)
  • 2020-11-22 05:33

    You can easily do with first you can make the div flex and apply justify content right or left and your problem is solved.

    <div style="display: flex;padding-bottom: 8px;justify-content: flex-end;">
    					<button style="font-weight: bold;outline: none;background-color: #2764ff;border-radius: 3px;margin-left: 12px;border: none;padding: 3px 6px;color: white;text-align: center;font-family: 'Open Sans', sans-serif;text-decoration: none;margin-right: 14px;">Sense</button>
    				</div>

    0 讨论(0)
提交回复
热议问题