如何在容器中居中放置表格?使用flex

时间:2019-09-14 19:29:26

标签: html css flexbox

我正在使用flex,我有一个容器,想要在其中有一个表单。这就是现在的样子。 enter image description here

所以,在那个蓝色的容器内,我希望表单看起来不错,并且居中。蓝色容器是柔线。这就是我在那个蓝色容器中所拥有的:

<div class="formulario">
    <form>
        First name:
        <input type="text" name="firstname"><br>
        Last name:
        <input type="text" name="lastname"><br>
        Email :
        <input type="text" name="email"><br>
        Username:
        <input type="text" name="username"><br>
        Password:
        <input type="password" name="password">
    </form>
</div>

这是CSS

.formulario {
    background-color: blue;
    flex : 3;
    display:flex;
    flex-direction: column;

    align-items: center;
    form{
        /*margin:3px; */
    }
}

我想将这些表单居中,并且理想情况下还要将它们间隔开一些,并使其相对于容器更大。

2 个答案:

答案 0 :(得分:1)

 
.formulario{
background-color: blue;
width:100vw;
height:100vh;
display:flex;
align-items:center;
justify-content:center;
}
<div class="formulario">
    <form>
      <table>
        <tr>
          <td>First name:</td>
          <td><input type="text" name="firstname"></td>
        </tr>
        <tr>
          <td>Last name:</td>
          <td><input type="text" name="lastname"></td>
        </tr>
        <tr>
          <td>Email:</td>
          <td><input type="text" name="email"></td>
        </tr>
        <tr>
          <td>Username:</td>
          <td><input type="text" name="username"></td>
        </tr>
        <tr>
          <td>Password:</td>
          <td><input type="password" name="password"></td>
        </tr>
      </table>
    </form>
</div>

答案 1 :(得分:0)

您可以使用Flexbox和CSS Grid实现此目的:

html,
body {
  height: 100%;
  margin: 0;
}

body {
  display: flex;
  flex-flow: column;
  min-height: 300px;
}

header {
  background: orange;
  height: 30px;
}

main {
  flex: 1;
  display: flex;
}

main .blue {
  background: rgb(60, 120, 230);
  flex: 10;
  display: flex;
  align-items: center;
  justify-content: center;
}

main .red {
  background: red;
  flex: 1;
}

.formulario > form {
  display: grid;
  grid-template-columns: 1fr 3fr;
  grid-gap: 7px;
}
<header></header>
<main>
  <div class="blue">
    <div class="formulario">
      <form>
        First name:
        <input type="text" name="firstname"> Last name:
        <input type="text" name="lastname"> Email :
        <input type="text" name="email"> Username:
        <input type="text" name="username"> Password:
        <input type="password" name="password">
      </form>
    </div>
  </div>
  <div class="red"></div>
</main>