html页面中,怎么能能让form表单在页面中居中,上下左右都居中。不分页面的大小,只在页面的中间显示

html-css020

html页面中,怎么能能让form表单在页面中居中,上下左右都居中。不分页面的大小,只在页面的中间显示,第1张

<STYLE type="text/css">

#login{

width:400px

height:280px

position:absolute

left: 50%

top: 50%

margin-left:-200px

margin-top:-140px

border:1px

background-color:red

align:center

}

#form{

width:300px

height:160px

position:relative

left:50%

top:50%

margin-left:-150px

margin-top:-80px

}

</STYLE>

</head>

<body>

<div id="login">

<div id="form">

<s:form action="" >

<s:textfield name="username" label="用户名" ></s:textfield>

<s:password name="password" label="密码" ></s:password>

<s:select list="{}" listKey="1" listValue="1" label="用户类型"></s:select>

<tr align="center">

<td colspan="2" align="center" valign="middle">

<s:submit value="登录" theme="simple"></s:submit>

<s:reset value="重置" theme="simple"></s:reset> </td>

</tr>

</s:form>

</div>

</div>

</body>

</html>

原理就是使用两个div,一个是绝对定位,一个是相对定位,绝对定位用于控制在浏览器中位置;相对定们的div把表单包起来,控制让其居中。

表单宽高不固定情况下,表单外面加一个父标签fa  表单加一个类centered

<body>   

<div class="fa">

<form name="search" method="post" action="#" class="centered">

   <input value="请输入关键词" type="text" name="q" />

   <input type="submit" value="搜索"/>

</form>

</div>

</body> 清除页面默认样式后(margin padding)

<style type="text/css"> 

html,body{width: 100%height: 100%}

.fa {text-align: centerheight: 100%}

.fa:before {content: ''display: inline-blockheight: 100%vertical-align: middle}

.centered {display: inline-blockvertical-align: middlebackground: redwidth: auto}

</style>

form本身不是可见元素,不能设置为居中,你说的应该是让里面显示的内容居中吧。可以在内嵌的div或外包的div中设置text-align,如果要整块内容居中,则可以设置外包的或内嵌的div(或其它容器)的margin-left和margin-right为auto。