CSS floats - how do I keep them on one line?

2019-01-12 14:41发布

I want to have two items on the same line using 'float: left' for the item on the left.

I have no problems achieving this alone. The problem is, I want the two items to stay on the same line even when you resize the browser very small. You know... like how it was with tables.

The goal is to keep the item on the right from wrapping no matter what.

So how to I tell the browser using css that I would rather stretch the containing div than wrap it so the the float: right; div is below the float: left; div?

example: what I want:

                                             \
 +---------------+  +------------------------/
 | float: left;  |  | float: right;          \
 |               |  |                        /
 |               |  |content stretching      \   Screen Edge
 |               |  |the div off the screen  /  <---
 +---------------+  +------------------------\
                                             /

10条回答
放我归山
2楼-- · 2019-01-12 15:30

Another option is, instead of floating, to set the white-space property nowrap to a parent div:

.parent {
     white-space: nowrap;
}

and reset the white-space and use an inline-block display so the divs stay on the same line but you can still give it a width.

.child {
    display:inline-block;
    width:300px;
    white-space: normal;
}

Here is a JSFiddle: https://jsfiddle.net/9g8ud31o/

查看更多
Ridiculous、
3楼-- · 2019-01-12 15:30

Are you sure that floated block-level elements are the best solution to this problem?

Often with CSS difficulties in my experience it turns out that the reason I can't see a way of doing the thing I want is that I have got caught in a tunnel-vision with regard to my markup ( thinking "how can I make these elements do this?" ) rather than going back and looking at what exactly it is I need to achieve and maybe reworking my html slightly to facilitate that.

查看更多
唯我独甜
4楼-- · 2019-01-12 15:34

Add this line to your floated element selector

.floated {
    float: left;
    ...
    box-sizing: border-box;
}

It will prevent padding and borders to be added to width, so element always stay in row, even if you have eg. three elements with width of 33.33333%

查看更多
来,给爷笑一个
5楼-- · 2019-01-12 15:37

i'd recommend using tables for this problem. i'm having a similar issue and as long as the table is just used to display some data and not for the main page layout it is fine.

查看更多
登录 后发表回答