html - 我怎样才能使这个表格居中?

标签 html css

我制作了一个适合宽屏的完美水平居中的登录表单。不知何故,小屏幕不是这种情况,即使我使用了视口(viewport)标记和 margin: 0 auto;。出了什么问题,我怎样才能正确地将它居中?

html,
body {
  width: 100%;
}

body {
  text-align: center;
}

fieldset {
  border: 1px groove black;
  border-radius: 5px;
}

form {
  font-family: Segoe UI;
  margin: 0 auto;
  margin-top: 15%;
  width: 27.5%;
}

input {
  border: 1px rgb(175, 175, 175) solid;
  border-radius: 5px;
  font-family: Helvetica;
  font-size: 100%;
  margin-top: 2.5%;
  padding: 1% 0% 1% 0%;
}

legend {
  font-size: 150%;
}

button {
  background-color: rgb(0, 117, 255);
  border: 0px;
  border-radius: 5px;
  color: white;
  cursor: pointer;
  transition: background-color 0.15s ease-out;
}

button:hover {
  background-color: rgb(0, 83, 255);
  transition: background-color 0.15s ease-in;
}

button#submit {
  font-size: 100%;
  margin-top: 7%;
  padding: 2.5% 10% 2.5% 10%;
}

button#signup {
  font-size: 100%;
  margin-top: 1%;
  padding: 0.6% 2.5% 0.6% 2.5%;
}
<!DOCTYPE html>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<html>

<head>
  <title>Login</title>
  <link rel="stylesheet" href="css/login.css">
</head>

<body>
  <form action="background_processing/login_process.php" enctype="multipart/form-data" method="post">
    <fieldset>
      <legend>Login</legend>
      <p>
        <label for="username">Username</label><br>
        <input type="text" id="username" name="username">
      </p>
      <p>
        <label for="password">Password</label><br>
        <input type="password" id="password" name="password">
      </p>
      <p>
        <button type="submit" id="submit">Log in</button>
      </p>
    </fieldset>
  </form><br>
  <button id="signup" onclick="window.open('https://google.com/','_self');">Sign up</button>
</body>

</html>

这是我的代码:https://jsfiddle.net/gabwvf68

最佳答案

这是您的问题区域:

    fieldset {
      border: 1px groove black;
      border-radius: 5px;
    }

    form {
      font-family: Segoe UI;
      margin: 0 auto;
      margin-top: 15%;
      width: 27.5%;
    }

我们可以简单地通过以下方式修复它:

    fieldset {
      border: 1px groove black;
      border-radius: 5px;
      width: 27.5%;
      margin: 0 auto;
    }

    form {
      font-family: Segoe UI;
      margin-top: 15%;
    }

将宽度和 margin: 0 auto; 移动到字段集。

margin 0 auto; 应该始终在您尝试居中的 block 而不是父 block 上。

关于html - 我怎样才能使这个表格居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56481361/

相关文章:

html - css 页脚在两侧切割

HTML相对路径,浏览器不附加域

javascript - 如何在 iPad 上使用 HTML5/Javascript 合成音频

html - 使用 div 创建垂直条

css - 只有背景图像必须在页面加载时淡入

html - CSS - 表格单元格边距?

jquery - 悬停时更改类的属性

javascript - 如何使输入和标签的父 div 切换子输入

html - 如何让我的导航栏加载到我的元素动画之上

javascript - 输入元素值呈现为 HTML 实体字符串而不是字符