首页 > 解决方案 > Bootstrap 页面中间的居中容器

问题描述

我是前端的新手,正在通过建立一个虚假的电子商务网站来练习。我遇到了一些问题,但遇到了一个我不确定解决它们的最佳方法的问题。我希望我的表单位于页面中间。它之所以复杂是因为我遇到了一个问题,即由于页面本身缺乏内容而导致我的视​​口太大,我的页脚下有一个巨大的空白。我解决这个问题的方法只是简单地将表单本身的视图高度设置为 85%,因此我不确定如何在页面上水平居中我的表单。解决此问题的最佳方法是什么?任何帮助是极大的赞赏!附上截图和代码 例子

代码如下:

{% extends 'base.html' %}
{% load static %}

{% block css_files  %}
<link rel="stylesheet" href="{% static 'login-out.css' %}">
{% endblock %}

{% block content %}
<div class="container-fluid" id='loginout'>
  <div class="container-fluid text-center pt-3">
  {% if next %}
    {% if user.is_authenticated %}
      <p>Your account doesn't have access to this page. To proceed,
      please login with an account that has access.</p>
    {% else %}
      <p><strong> Please login to see this page.</strong></p>
    {% endif %}
  {% endif %}
    </div>
    
  <section id="form-test">
  <div class="container w-25 py-3" id='login-wrapper'>
    <form method="post" action="{% url 'login' %}">
        {% csrf_token %}
        <div class="form-group">
            {{ form.username.label_tag }}
            {{ form.username }}
            {{ form.password.label_tag }}
            {{ form.password }}
            {{ form.non_field_errors }}
        </div>
        <input class='btn btn-outline-primary' type="submit" value="Login" />
        <input type="hidden" name="next" value="{{ next }}" />
    </form>
    
    {# Assumes setup the password_reset view in URLconf #}
    <p><a href="{% url 'password_reset' %}">Lost password?</a></p>
  </div>
  </section>
</div>
{% endblock %}

和CSS

#loginout {
    background: #fef8f5;
    height: 85vh;
}

#container-text-center-pt-3 a {
    text-decoration: none !important;
}

#wrapper {
    background: #fef8f5;
    height: 100vh;
}

.form-control:focus {
    border-color: #d66534;
    box-shadow: 0 0 0 0.2rem rgb(230, 77, 11, 0.25);
} 

#login-wrapper {
    background-color: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
}

标签: htmlcssbootstrap-4

解决方案


要使容器垂直居中,您必须将父级设置为最小高度 100vh 和高度 100%,然后您可以将 flex 添加到父级以使其居中。下面的一个例子:

HTML:

<div class="parent container d-flex justify-content-center align-items-center h-100">
  <div class="child"> <!-- Your code goes inside this div/form --> </div>
</div>

请注意,h-100 表示“高度:100%”,因此您应该使用一些 CSS 来解决它:

.parent {
  min-height: 100vh;
}

而且,友情提示,“父母”就像“身体”。如果身体不是 100vh,您将无法使其居中。换句话说,如果“body”是 100vh,它的孩子应该是 100%。如果您的结构更像:

<body><div><div><div class="me"><form></form></div></div></div></body>

你的身体应该是“最小高度:100vh;高度:100%”,你所有的 div 应该是“高度:100%”。然后,您应该将 flex 类添加到表单的父级(具有“me”类的那个)。希望它可以帮助你。我鼓励你学习 CSS 盒子模型,它会帮助你理解一切。请避免使用“位置:绝对”技术。

在这里您可以了解有关盒子模型的更多信息:https ://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model


推荐阅读