I would like to center some html elements in my html page, for example a label. I want to accomplish this by using JQuery and CSS. Unfortunately I'm not familiar with JQuery.
我想在我的html页面中居中一些html元素,例如标签。我想通过使用JQuery和CSS来实现这一目标。不幸的是我不熟悉JQuery。
I just need a little help from you guys.
我只需要你们的帮助。
Thank you.
4 个解决方案
#1
3
try this simple function:
试试这个简单的功能:
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
return this;
}
//Use the above function as:
$(element).center();
#2
3
Presentation is NOT a task for jQuery.
演示文稿不是jQuery的任务。
CSS:
label {display:block;text-align:center}
#3
2
I agree that the best way to do this is through pure css, but this is a very brute force way to do it....
我同意这样做的最好方法是通过纯粹的CSS,但这是一种非常强力的方式来做到这一点....
html
<div id="centerme">content</div>
css
#centerme {
position: absolute;
}
jquery
$(window).onLoad(this.resize);
$(window).resize(this.resize);
resize = function() {
var center = ($(window).width/2) - ($('#centerme').width/2);
$('.centerme').css('left', center+'px');
}
#4
1
Check this DEMO http://jsfiddle.net/yeyene/tGbxj/1/
查看此演示http://jsfiddle.net/yeyene/tGbxj/1/
JQUERY
$(document).ready(function() {
verCenter('#red');
verCenter('#blue');
$(window).resize(function(){
verCenter('#red');
verCenter('#blue');
});
});
function verCenter(element){
var ver_top = ($(window).height() - $(element).height()) / 2;
$(element).css( "margin-top", ver_top+'px' );
}
#1
3
try this simple function:
试试这个简单的功能:
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
return this;
}
//Use the above function as:
$(element).center();
#2
3
Presentation is NOT a task for jQuery.
演示文稿不是jQuery的任务。
CSS:
label {display:block;text-align:center}
#3
2
I agree that the best way to do this is through pure css, but this is a very brute force way to do it....
我同意这样做的最好方法是通过纯粹的CSS,但这是一种非常强力的方式来做到这一点....
html
<div id="centerme">content</div>
css
#centerme {
position: absolute;
}
jquery
$(window).onLoad(this.resize);
$(window).resize(this.resize);
resize = function() {
var center = ($(window).width/2) - ($('#centerme').width/2);
$('.centerme').css('left', center+'px');
}
#4
1
Check this DEMO http://jsfiddle.net/yeyene/tGbxj/1/
查看此演示http://jsfiddle.net/yeyene/tGbxj/1/
JQUERY
$(document).ready(function() {
verCenter('#red');
verCenter('#blue');
$(window).resize(function(){
verCenter('#red');
verCenter('#blue');
});
});
function verCenter(element){
var ver_top = ($(window).height() - $(element).height()) / 2;
$(element).css( "margin-top", ver_top+'px' );
}