Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

css - How to float an element left with full height of the wrapper?

HTML:

<div class="wrapper">
    <div class="left">
        Foo
    </div>
    <div class="right">
        Text row 1
    </div>
</div>

<div class="wrapper">
    <div class="left">
        Foo Bar
    </div>
    <div class="right">
        Text row 1<br>
        Text row 2<br>
        Text row 3
    </div>
</div>

CSS:

.wrapper {
    overflow:hidden;
}

.left {
    width:80px;
    float:left;
    height:100%;
}

How can I give the floating div the full height of the wrapper (whose height is varying)?

is it possible without jQuery?

Test: http://jsfiddle.net/Q6B43/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The display: table solution

Within tables each cell of a row has the same height.

.wrapper {
    display: table;
    width: 100%;
}
.left, .right {
    display: table-cell;
}

This is the best solution in my opinion, but is not compatible before IE8.

Here is the Fiddle for this solution.

Using absolute positioning

Absolute positioned elements respect their relative parents height:

.wrapper {
    position: relative;
    padding-left: 85px;
}
.left {
    position: absolute;
    left: 0;
    top: 0;
}

Normally I would not recommend absolute positioning in most situations. But as you have a fixed width anyway, maybe it does not matter. But be aware of the fact that this will ignore long contents in .left. The height is just controlled by .right.

Here is an update to your Fiddle.

The flexible solution

This is so new I would not recommend using it right now, but just to be complete. You could use CSS3 flex, but be aware of browser compatibility:

.wrapper {
    display: flex;
}

The Fiddle (tested in current Chrome and Firefox).

The grid layout

Even newer than flexbox, CSS grid seams to be the perfect answer for layout questions.

.wrapper {
    display: grid;
    grid-template-areas: 'left right';
}

.left {
    grid-area: left;
}

.right {
    grid-area: right;
}

Browser compatibility is rare, if you go back a view versions. Besides, it would be overkill for the OP's scenario in my opinion, but for more complex layout troubles in the future, this is a very powerful thing.

See it in the Fiddle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...