如何将一个div定位在屏幕底部中心

47

我有这段 CSS:

#manipulate
{
  position:absolute;
  width:300px;
  height:300px;
  background:#063;
  bottom:0px;
  right:25%;
}

我有以下的HTML代码:

<div id="manipulate" align="center">

</div>

我们怎样才能把那个div定位在屏幕底部中间位置?!?

9个回答

89
如果你不喜欢使用负边距,看看这个。

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

特别适用于您不知道div的宽度时。

43

align="center"没有效果。

由于您使用了position:absolute,我建议将其从左侧定位到50%,然后从左边距中减去一半的宽度。

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

嗯...有什么解决方案吗?无论如何,我能把它设置到中心吗? - BlackFire27
1
你可以动态地将 margin-left 设置为 -50%,而不是给定一个静态值。 - Dev_noob
我投入时间是因为这个CSS导致我的文本被移除,把div放到了屏幕末尾。 - Salman Mushtaq
2
我不理解。为什么要从左边距中减去一半的宽度? - Mayank Kataria
@MayankKataria 我的理解是因为 left: 50% 将左侧放置于中心位置,而不是将中间放置于中心位置。 - Jeppe

22

使用负边距:

#manipulate
{
  position:absolute;
  width:300px;
  height:300px;
  margin-left:-150px;
  background:#063;
  bottom:0px;
  left:50%;
}

关键在于使用 widthleftmargin-left 属性。


谷歌搜索“position absolute center”,你会找到关于这个主题的文章。 - Alex
4秒钟足以产生巨大的影响。 :P - Purag
非常正确...我今天面试时被要求做到这一点...但我没能做到 :(....我希望我有谷歌访问权限 :( - BlackFire27
不要太担心,现在你知道了 :) 他们显然是在探究你的知识水平,而你只有在需要使用它时才会知道这个小技巧... - Alex
这个在HTML直接作为样式参考会起作用吗?不需要CSS... style="position:absolute;width:300px;height:300px;margin-left:-150px;background:#063;bottom:0px;left:50%;" - Empire of E

14

这里有一个使用两个div的解决方案:

HTML:

    <div id="footer">
        <div id="center">
            Text here
        </div>
    </div>

CSS:

#footer {
    position: fixed;
    bottom: 0;
    width: 100%;
}
#center {
    width: 500px;
    margin: 0 auto;
}

6

使用 Flexbox 对我有帮助:

#manipulate {
  position: absolute;
  width: 100%;
  display: flex;
  justify-content: center; // Centers the item
  bottom: 10px; // Moves it up a little from the bottom
}

2
您可以使用负边距将其居中,但请注意,如果未设置任何包含的 div 为 position:relative,则它会精确地居中于屏幕中心。
例如。http://jsfiddle.net/aWNCm/ 因此,最好的方法是为其包含的 divs 设置正确的位置属性,否则它将以某些随机的方式丢失居中效果。

1

首先创建一个容器,这样您就可以更自由地移动它:

<div class="container">
  <div id="manipulate"></div>
</div>

然后:

.container{
  height: 100vh; ------>adjust it. Should fit wherever you need to put it
  display: flex;
  flex-direction: column;
  justify-content: end;
}

#manipulate{
  width: min(70vw - 5px, 750px); ------>responsive stuff
  height: 90vh;
  margin-inline: auto;
}

0

100%工作的单行(内联CSS解决方案)

<div style="padding: 20px; width: 100%; text-align: center;">Your Content Here</div>

0

100%可行的单行(内联CSS解决方案)

<div style="position: fixed; bottom: 10px; width: 100%; text-align: center;">Your Content Here</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接