我的html出了问题。我有这个基本的HTML登录页面:
<section>
<form id="" name="" method="post" action="">
<label for="username">User:</label>
<input type="text" id="username" name="username" />
<label for="password">Password:</label>
<input type="password" id="password" name="password" />
<input type="submit" id="login" name="login" value="Entrar" />
</form>
</section>
问题是,如何在页面中水平和垂直地集中此部分,固定宽度,BUT,高度自动独立于内容?
CSS示例:
section { width: 300px; }
如果仅使用CSS不可能,则jQuery被禁用。
答案 0 :(得分:4)
使用jQuery,您可以通过
执行此操作section
元素的高度。section
元素的margin-top设为最终数字。像这样:
var ht = $(window).height();
var sectionHt = $('section').height();
var pad = (ht - sectionHt)/2;
$('section').css('margin-top',pad);
例如:http://jsfiddle.net/JMC_Creative/8RpQZ/
或者,如果您希望它在调整窗口大小时保持居中,则执行相同的操作,但将其包装在$(window).resize()
jQuery方法中。像这样:
$(window).resize(function(){
var ht = $(window).height();
var sectionHt = $('section').height();
var pad = (ht - sectionHt)/2;
$('section').css('margin-top',pad);
});
答案 1 :(得分:1)
<section>
<form id="" name="" method="post" action="">
<label for="username">User:</label>
<input type="text" id="username" name="username" />
<label for="password">Password:</label>
<input type="password" id="password" name="password" />
<input type="submit" id="login" name="login" value="Entrar" />
</form>
</section>
section {
width: 300px;
height: auto;
margin: 0 auto;
position: relative;
top: 250px; /* pixels from top of page - if you have the height to be auto, may see different changes, however, this could be what you want if you want the form to be in the exact center -- simply change the px's to suit your needs */
}
这是你要问的吗?演示:http://jsfiddle.net/zyFG5/
修改强>
好的,试一试:
<section>
<form id="" name="" method="post" action="">
<label for="username">User:</label>
<input type="text" id="username" name="username" />
<label for="password">Password:</label>
<input type="password" id="password" name="password" />
<input type="submit" id="login" name="login" value="Entrar" />
</form>
</section>
section {
width: 300px;
height: 300px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -150px;
}
负边距正好是高度和宽度的一半,将元素拉回到完美的中心。仅适用于固定高度/宽度的元素。
答案 2 :(得分:0)
一点css可以帮助你实现你的目标。虽然可能需要一些调整才能得到你想要的东西。
将您的部分设置为相对位置,以便您可以垂直对齐。然后设置一个自动左/右边距,使其水平居中...
section{position:relative;top:200px;
margin:auto;
width:300px;
border:2px outset #0af;
text-align:right;
background-color:#fff;
padding:6px;
}
另一种方式是有点hacky,但似乎工作正常。您创建一个高度为100%且不可见的div,并将您的部分垂直对齐。
这是你可以分叉的东西...... http://codepen.io/lukeocom/pen/Dmdnh
答案 3 :(得分:0)
使用jquery:
$(function(){
var height = $(window).height();
var width = $(window).width();
var blockHeight = $(".block").height();
var blockWidth = $(".block").width();
var paddingTop = (height/2 - blockHeight);
var paddingWidth = (width/2 - blockWidth);
$(".block").css({
'padding-top':paddingTop,
'padding-left':paddingWidth
});
});