首页 > 解决方案 > 无法使用 CSS 定位将按钮定位在底部,而是在顶部

问题描述

我不明白这里发生了什么。我想在我的 div 底部放一个按钮。所以我将父元素的位置设置为absolute,然后将我的元素设置为relative位置。但相反,它位于顶部而不是底部。这太奇怪了,我不明白为什么会这样。

在此处输入图像描述

这是我的html

<!DOCTYPE html>
<html>
<head>
  <style>
    body{
      background-color: #f3f2f4;
    }
    .header{
        width: 105%;
        height: 117px;
        left: -11px;
        position: absolute;
        background-image: linear-gradient(#8bc2e0, #4f9bc6);
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        border-bottom-left-radius: 100% 70%;
        border-bottom-right-radius: 100% 70%;
    }
    .container{
      width:450px;
      height:70vh;
      background-color:white;
      border-radius:6px;
      position:absolute;
      top:50%;
      overflow:hidden;
      left:50%;
      transform:translate(-50%,-50%);
    }

    .logo {
        width: 100px;
        margin: 0 auto;
        margin-top: 46px;
    }

    .button {
        width: 80%;
        margin: 0 auto;
        padding: 15px 20px;
        font-size: 17px;
        color: #fff;
        border-radius: 30px;
        background: #428cb5;
        display: flex;
        align-items: center;
        justify-content: center;
        font-family: Arial;
        cursor: pointer;
        transition: .2s;
        position: absolute;
        bottom: 0px;
    }

    .button:hover {
        background: #4895bf;
    }

    .body {
        position: relative;
    }
  </style>
</head>
<body>
    <div class="container">
        <div class="body">
            <div class="header">
                <div class="logo">

                </div>
            </div>  

            <div class="button">Submit button</div>
        </div>
    </div>
</body>
</html>

这是一个小提琴: https ://jsfiddle.net/n35e6Lzh/

标签: htmlcss

解决方案


你不应该在身体上方使用任何 div。删除标题和按钮中的绝对位置,并在容器中使用这 3 个属性:

display: flex;
flex-direction: column;
justify-content: space-between;

https://jsfiddle.net/wtpyjhae/


推荐阅读