How can I position my div at the bottom of its con

2018-12-31 09:47发布

Given the following HTML:

<div id="container">
  <!-- Other elements here -->
  <div id="copyright">
    Copyright Foo web designs
  </div>
</div>

I would like #copyright to stick to the bottom of #container.

Can I achieve this without using absolute positioning? If the float property supported a value of 'bottom' it seems that would do the trick, but unfortunately, it doesn't.

标签: html css
21条回答
梦醉为红颜
2楼-- · 2018-12-31 10:16

Actually, the accepted answer by @User will only work if the window is tall and the content is short. But if the content is tall and the window is short, it will put the copyright info over the page content, and then scrolling down to see the content will leave you with a floating copyright notice. That makes this solution useless for most pages (like this page, actually).

The most common way of doing this is the "CSS sticky footer" approach demonstrated, or a slightly slimmer variation. This approach works great -- IF you have a fixed height footer.

If you need a variable height footer that will appear at the bottom of the window if the content is too short, and at the bottom of the content if the window is too short, what do you do?

Swallow your pride and use a table.

For example:

* {
    padding: 0;
    margin: 0;
}

html, body {
    height: 100%;
}

#container {
    height: 100%;
    border-collapse: collapse;
}
<!DOCTYPE html>
<html>
<body>
    <table id="container">
        <tr>
            <td valign="top">
                <div id="main">Lorem ipsum, etc.</div>
            </td>
        </tr>
        <tr>
            <td valign="bottom">
                <div id="footer">Copyright some evil company...</div>
            </td>
        </tr>
    </table>
</body>
</html>

Try it out. This will work for any window size, for any amount of content, for any size footer, on every browser... even IE6.

If you're cringing at the thought of using a table for layout, take a second to ask yourself why. CSS was supposed to make our lives easier -- and it has, overall -- but the fact is that even after all these years, it's still a broken, counter-intuitive mess. It can't solve every problem. It's incomplete.

Tables aren't cool, but at least for now, they are sometimes the best way to solve a design problem.

查看更多
临风纵饮
3楼-- · 2018-12-31 10:17

There is nothing called float:bottom in CSS. The best way is using positioning in such cases:

position:absolute;
bottom:0;
查看更多
情到深处是孤独
4楼-- · 2018-12-31 10:18

If you want it to "stick" to the bottom, regardless of the height of container, then absolute positioning is the way to go. Of course, if the copyright element is the last in the container it'll always be at the bottom anyway.

Can you expand on your question? Explain exactly what you're trying to do (and why you don't want to use absolute positioning)?

查看更多
登录 后发表回答