在(zai)HTML5中,表单将表单居中的居中方法有很多种,这里我将(jiang)介绍两种(zhong)常用的表单方法:使用CSS样式和使用Flexbox布局。(图片来源网络,居中侵删)
方法一:使用(yong)CSS样式

我们需要创建一个HTML文件,表单然(ran)后在其中添加一个表(biao)单,居中接下来,表(biao)单我们将使用CSS样式来控制表单的(de)居中居中显示。

1、表单创建HTML文件:

<!DOCTYPE html><html lang="zh"><head> <meta charset="UTF8"> <meta name="viewport" content="width=devicewidth,居中 initialscale=1.0"> <title>表(biao)单居中(zhong)示例</title> <link rel="stylesheet" href="styles.css"></head><body> <div class="container"> <form> <label for="username">用户名:</label> <input type="text" id="username" name="username"> <br> <label for="password">密码:</label> <input type="password" id="password" name="password"> <br> <input type="submit" value="提交"> </form> </div></body></html>2、创建CSS文(wen)件(styles.css):
body { display: flex; justifycontent: center; alignitems: center; height: 100vh; margin: 0;}.container { display: flex; flexdirection: column; alignitems: center;}在这个例子中,表单我们使用了CSS的居中display: flex属性(xing)来创建一个弹性容器,然后使用justifycontent和(he)alignitems属性来控制容器内(nei)元素的表单水平和垂直居中,我(wo)们还为body元素设置了height: 100vh,居中(zhong)使其占据整个视口高度,表单我(wo)们将表单放置在一个名为container的子容器中,并使(shi)用flexdirection: column属性将其内容排列为垂直方向。
方法二:使(shi)用Flexbox布局
1、修改HTML文件:
<!DOCTYPE html><html lang="zh"><head> <meta charset="UTF8"> <meta name="viewport" content="width=devicewidth, initialscale=1.0"> <title>表单居中示例</title> <link rel="stylesheet" href="styles.css"></head><body> <form class="flexcenter"> <label for="username">用(yong)户名:</label> <input type="text" id="username" name="username"> <br> <label for="password">密码:</label> <input type="password" id="password" name="password"> <br> <input type="submit" value="提(ti)交"> </form></body></html>
2、修改CSS文件(jian)(styles.css):
.flexcenter { display: flex; justifycontent: center; alignitems: center; height: 100vh;}在这个例子中,我们为表单添加了一个名为(wei)flexcenter的类(lei),该类包含了display: flex、justifycontent: center和alignitems: center属性,这样,表单就会自动在其父容器中居中显示,我们还为body元素设置了height: 100vh,使其占据整个视口高度。