开发者

Floating a div without specifying a width

开发者 https://www.devze.com 2022-12-16 17:01 出处:网络
I can float an image on the left and have the text wrap around it no problem just by specifying float: left on the image. Like this:

I can float an image on the left and have the text wrap around it no problem just by specifying float: left on the image. Like this:

<div id='foo'>

  <img src='bar' alt='baz' style='float: left;' />
  Lorem ipsum...

</div>

However if the image is wrapped in a div like the following i cannot achieve the same effect without declaring a fixed width on both the div#image_container and the div#text_container

<div id='image_container'>
  <img src='blah' alt='blah' />
</div>

<div id='text_container'>
  Lorem ipsum... long text
</div>

Is there a way to keep the flexibility of the first solution and avoid dec开发者_开发百科laring a width and have the div#image_container float next to the div#text_container?


Try setting overflow: hidden on the wrapper div, that should automatically set the div to the width of the image.


OK maybe I misunderstood your question. Do you just want the text to flow around the image? If so, all you should need is this CSS:

#text_container { display: inline; }


#text_container,
#image_container {
  display: inline;
}

should do it. Try this:

<html>
    <head>
    <style>
        #top {
            float: left;
            display: inline;
            border: 1px solid green;
        }

        #bottom {
            float: right;
            display: inline;
            border: 1px solid red;
        }
    </style>
    </head>
    <body>
    <div id="top">
        I'm the top div
    </div>
    <div id="bottom">
        I'm the bottom div
    </div>
</html>

But if the content of your div's is bigger than the width you've left for them (which it probably is) then you will struggle. You should really give it a width but the above might work for you depending on how you want to use it.


Instead of the text container use a paragraph tag (<p></p>). It will wrap around the content plus it is more accessible and semantic.

0

精彩评论

暂无评论...
验证码 换一张
取 消