【问题标题】:Center a DIV at bottom of page在页面底部居中 DIV
【发布时间】:2014-10-10 19:06:58
【问题描述】:

我试图在页面底部居中放置一个 div,但没有运气。我在网上搜索过,但在尝试应用他们的解决方案时却一无所获。

那里的任何人都可能有解决方案吗?见以下代码:

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script></script>
<style type="text/css">
body {
    background-color: aqua;
    height:100%;
    min-height:100%;
}
.centerDiv {
    display: table;
    width:90%; 
    margin:0 auto;
    height:100%;
    min-height:100%;
    text-align: center;
}
.box {
    display: inline-block;
    width: 100px;
    height:100px;
    border: 3px solid #fff;
} 
</style>
</head>
<body>
<div class="centerDiv">
    <div class="box box1" style="background-color:#585858;"> </div>
    <div class="box box2" style="background-color:#118C4E;"> </div>
    <div class="box box3" style="background-color:#C1E1A6;"> </div>
    <div class="box box4" style="background-color:#FF9009;"> </div>
</div>
</body> 
</html>

【问题讨论】:

标签: html css


【解决方案1】:

我认为您的意思是,您的 div 将位于页面底部。这将对您有所帮助:

.centerDiv {
    display: block;
    width: 100%; 
    margin: 0 auto;
    height: auto;
    text-align: center;
    position: fixed;
    bottom: 0;
}

将位置设置为fixed,并且 div 将随时(向下滚动时)停留在某个位置。

【讨论】:

  • 做到了!谢谢!我一直在用头撞墙,而你让它看起来很容易。太棒了。
  • 请记住选择正确答案。另请注意,这意味着即使您向上或向下滚动页面,该框也将位于视口(窗口)的底部,这与一直停留在页面底部的页脚不同。
  • 是的,我提醒了,fixed 会将元素设置在一个固定的位置。我想说,将位置更改为relative 也会将其设置为底部,但位于文档的末尾。位置absolute 可以做同样的事情,但这取决于你的其他元素(或者你想要它做什么),否则它可能会破坏你的整个页面。
【解决方案2】:

您遇到的问题是该框在技术上已经位于页面底部 - 页面会扩展以适应内容,而不是窗口。如果您希望该框始终位于窗口的底部,则需要使用position: fixed,无论滚动多少,它都会位于窗口底部或者页面有多短/多高。

See the demo here for the result with the fixed position.

.centerDiv {
    width:100%; 
    text-align: center;
    position: fixed; 
    bottom: 0;
}
.box {
    display: inline-block;
    width: 100px;
    height:100px;
}

现在,如果您希望框始终位于页面底部,除非页面高度小于窗口高度(在这种情况下它将位于窗口底部),您将有麻烦。这对 CSS 来说有点困难。但是,如果您不介意使用脚本,那么使用 jQuery 很容易:

See the demo here for the result using jQuery.

var minheight = $(window).height();
$("body").css("min-height", minheight);

body {
    position: relative;
    padding: 0;
    margin: 0;
    height: 100%; 
}
.centerDiv {
    width:100%; 
    text-align: center;
    position: absolute; 
    bottom: 0;
}
.box {
    display: inline-block;
    width: 100px;
    height:100px;
    border: 3px solid #fff;
}

【讨论】:

    【解决方案3】:

    div 元素有一个align 属性,所以它可以提供帮助:

    <div align="center"></div>
    

    【讨论】:

    • align 属性已过时
    • 建议:HTML5 不支持
      align 属性。改用 CSS。
    猜你喜欢
    • 1970-01-01
    • 2010-10-05
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 2016-12-30
    • 1970-01-01
    相关资源
    最近更新 更多