开发者

For CSS, why 2 floats in a table cell don't float on the same level?

开发者 https://www.devze.com 2023-03-08 19:27 出处:网络
If two divs are floated in a table cell, and the text are short, they float nicely on the same level.

If two divs are floated in a table cell, and the text are short, they float nicely on the same level.

But when the second div has longer text, the 2 divs now don't float on the same level.

Why is that and how to make it work, without specifying a hard-coded width for the 2nd div? (because dynamic width is needed if other table cells are wider or not a开发者_运维技巧s wide)

A code example is in: http://topics2look.com/code-examples/two-floats-in-a-table/

The first hello is floated left (it actually is supposed to be an image of + or - using CSS image sprite, but just made simple here). The "world world" is supposed to be the description and float nicely next to the image.

So the first table is all ok. But in the second table, it has "world world world ... world" and is quite long. Now the second div will not float next to it but will float under the first float. Is there a way to make it shrink wrap better so that it floats nicely next to the first div?


don't float the second div, then add overflow: hidden; (or auto) to it to make is anew block formatting context, should achieve what you need:

CSS:

body { 
   font: 16px Verdana, sans-serif;
}

#main-content { 
   width: 600px; 
   border: 6px double black; 
   margin: 20px 0;
}
table { 
   border: 6px double orange;
}

table div { 
   float: left; 
   padding: 4px;
}

table div+div {
   float: none; 
   overflow: hidden;
}

HTML:

<table>
   <tr>
      <td><div>hello</div> <div>world world world world world world world world world</div></td>
      <td><div>hello</div> <div>world world world world world world world</div></td>
   </tr>
</table>


Any element that you float becomes a block-level element. That's why when the two blocks are too wide to sit next to each other the second block floats under the first one.

I don't know that there is a solution in this case without setting the width of the elements, but I am curious to know what you're trying to achieve with this.


My guess is that there's a better way to accomplish what you are trying to do. I am also curious what your goal is here; floats work exactly this way for good reason.

If you absolutely must have them resize dynamically in this paradigm, you could always use javascript.

0

精彩评论

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