jQuery 使用jQuery垂直和水平居中div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13903556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Centering a div vertically & horizontally using jQuery
提问by user1807777
I am using this script to center my div horizontally and vertically.
我正在使用此脚本将我的 div 水平和垂直居中。
When the page loads the div gets centered vertically, not horizontally until I resize the browser.
当页面加载时,div 会垂直居中,而不是水平居中,直到我调整浏览器的大小。
What am I doing wrong?
我究竟做错了什么?
$(document).ready(function (){
$(window).resize(function (){
$('.className').css({
position:'absolute',
left: ($(window).width() - $('.className').outerWidth())/2,
top: ($(window).height() - $('.className').outerHeight())/2
});
});
$(window).resize();
});
回答by Dim13i
I normally use this "technique":
我通常使用这种“技术”:
$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : -$('.className').width()/2,
'margin-top' : -$('.className').height()/2
});
});
UPDATE:
更新:
I'm updating the solution, as suggested by the user Fred K, using .outerWidth()
and .outerHeight()
to have a more precise centering.
我正在更新解决方案,正如用户Fred K所建议的那样,使用.outerWidth()
和.outerHeight()
以获得更精确的居中。
$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : -$('.className').outerWidth()/2,
'margin-top' : -$('.className').outerHeight()/2
});
});
Some additional notes from jQuery' documentation (.outerWidth()
, .outerHeight()
):
来自 jQuery 文档 ( .outerWidth()
, .outerHeight()
) 的一些附加说明:
The number returned by dimensions-related APIs, including .outerWidth(), may be fractional in some cases. Code should not assume it is an integer. Also, dimensions may be incorrect when the page is zoomed by the user; browsers do not expose an API to detect this condition.
The value reported by .outerWidth() is not guaranteed to be accurate when the element's parent is hidden. To get an accurate value, you should show the parent first, before using .outerWidth().
在某些情况下,与维度相关的 API(包括 .outerWidth())返回的数字可能是小数。代码不应假定它是一个整数。此外,当用户缩放页面时,尺寸可能不正确;浏览器不会公开 API 来检测这种情况。
当元素的父元素隐藏时,.outerWidth() 报告的值不能保证准确。要获得准确的值,您应该在使用 .outerWidth() 之前先显示父级。
UPDATE 2:
更新 2:
A simple update to show how you could use this
inside the css()
method in case there are more elements with the same class
tag with different sizes.
一个简单的更新,展示了如何this
在css()
方法内部使用,以防有更多class
具有不同大小的相同标签的元素。
$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : function() {return -$(this).outerWidth()/2},
'margin-top' : function() {return -$(this).outerHeight()/2}
});
});
回答by Jai
use this to center:
用它来居中:
$.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2 + "px");
this.css("left", ( $(window).width() - this.width() ) / 2 + "px");
return this;
}
$('yourElem').center();
回答by charlietfl
Wrap the handler code in a function so you can call that function both on page load as well as handler for $(window).resize()
将处理程序代码包装在一个函数中,以便您可以在页面加载和处理程序中调用该函数 $(window).resize()
/* use as handler for resize*/
$(window).resize(adjustLayout);
/* call function in ready handler*/
$(document).ready(function(){
adjustLayout();
/* your other page load code here*/
})
function adjustLayout(){
$('.className').css({
position:'absolute',
left: ($(window).width() - $('.className').outerWidth())/2,
top: ($(window).height() - $('.className').outerHeight())/2
});
}
回答by Matthias
Related to your code snippet, you need to set the position first:
与您的代码片段相关,您需要先设置位置:
$(window).resize(function (){
var $el = $('.className');
$el.css('position', 'absolute').css({
left: ($(window).width() - $el.width()) / 2,
top: ($(window).height() - $el.height()) / 2
});
});
Maybe you could set the position attribute via a staticCSS style.
也许您可以通过静态CSS 样式设置位置属性。
回答by mabi
based on @dimi's answer, works better with multiple elements
基于@dimi 的回答,使用多个元素效果更好
$(".className").each(
function () {
$( this ).css("position","absolute");
$( this ).css("left","50%");
$( this ).css("margin-left", - $( this ).outerWidth()/2 );
$( this ).css("top","50%");
$( this ).css("margin-top", - $( this ).outerHeight()/2 );
return this;
}
);
回答by Mustafah
I use this JQuery.centerplugin to center my DOM elements. The code will be something like this:
我使用这个JQuery.center插件来居中我的 DOM 元素。代码将是这样的:
$("#child").center()
The prior code will center relative to its direct parent, if you need to center relative to another parent, it will be:
先前的代码将相对于其直接父级居中,如果您需要相对于另一个父级居中,它将是:
$("#child").center($("#parent"))
There are customized options, if you need other form of centralization.
如果您需要其他形式的集中化,可以使用自定义选项。
回答by Celdor
I have recently been trying to place a box in the middle of a browser window. I created the code below. The jQuery script is quite long because I took into account all paddings and margins of html and body tags, if someone have set them. If one does not care about the backgrounds, then only winwidth, winheight, toppx, leftpx, and "#container" have to be set. The rest may be deleted.
我最近一直在尝试在浏览器窗口中间放置一个框。我在下面创建了代码。jQuery 脚本很长,因为我考虑了 html 和 body 标签的所有填充和边距,如果有人设置了它们。如果不关心背景,那么只需设置 winwidth、winheight、toppx、leftpx 和 "#container"。其余的可以删除。
<!DOCTYPE html>
<html>
<head>
<title>Test of centre of container</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style>
html {
background-color: #444;
margin: 30px;
}
#wrapper {
background-color: #777;
width: 75%;
margin: 0 auto;
padding: 0;
}
#container {
background-color: #ddd;
border-radius: 10px;
box-shadow: 0 0 2px #222;
width: 200px;
height: 100px;
position: absolute;
vertical-align: middle;
}
#extext {
text-align: center;
padding: 0;
}
</style>
</head>
<body>
<script>
function setDimensions() {
var winwidth = $(window).width();
var winheight = $(window).height();
var htmlmv = parseInt($("html").css("margin-top")) + parseInt($("html").css("margin-bottom"));
var htmlpv = parseInt($("html").css("padding-top")) + parseInt($("html").css("padding-bottom"));
var htmlmh = parseInt($("html").css("margin-left")) + parseInt($("html").css("margin-right"));
var htmlph = parseInt($("html").css("padding-left")) + parseInt($("html").css("padding-right"));
var bodymv = parseInt($("body").css("margin-top")) + parseInt($("body").css("margin-bottom"));
var bodypv = parseInt($("body").css("padding-top")) + parseInt($("body").css("padding-bottom"));
var bodymh = parseInt($("body").css("margin-left")) + parseInt($("body").css("margin-right"));
var bodyph = parseInt($("body").css("padding-left")) + parseInt($("body").css("padding-right"));
var vspace = htmlmv + htmlpv + bodymv + bodypv;
var hspace = htmlmh + htmlph + bodymh + bodyph;
var wrapheight = winheight - vspace;
var wrapwidth = winwidth - hspace;
$("#wrapper").height(wrapheight);
// $("#wrapper").width(wrapwidth);
var toppx = (winheight - parseInt($("#container").css("height"))) / 2;
var leftpx = (winwidth - parseInt($("#container").css("width"))) / 2;
$("#container").css("top", toppx.toString() + "px");
$("#container").css("left", leftpx.toString() + "px");
}
$(document).ready(function () {
setDimensions();
});
$(window).resize(function () {
setDimensions();
});
</script>
<div id="wrapper">
<div id="container">
<p id="extext">Example text</p>
</div>
</div>
</body>
</html>
EDIT: I found much better solution for this on CSS Tricks websiteand it uses only CSS :). The code's below:
编辑:我在CSS Tricks 网站上找到了更好的解决方案,它只使用 CSS :)。代码如下:
<!DOCTYPE html>
<html>
<head>
<title>
Test centring!
</title>
<style>
body div {
background-color: red;
box-shadow: 0 0 15px #222;
border-radius: 10px;
padding: 10px;
margin: -150px auto auto -200px;
width: 380px;
height: 280px;
position: absolute;
top: 50%;
left: 50%;
text-align: center;
line-height: 140px;
}
body div h2 {
color: yellow;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div>
<h2>
Example text<br />
Example Text
</h2>
</div>
</body>
</html>
回答by Lukas Liesis
my div with class center has to be centered horizontally in the middle and it's position is fixed. I use this small code to make it happen:
我的类中心 div 必须在中间水平居中,并且它的位置是固定的。我使用这个小代码来实现它:
$(window).on('resize load', function () {
$('.center').each(function () {
$(this).css({
'margin-left': ($('body').width() - $(this).width()) / 2
});
});
});
you can use same tactics for horizontal alignment too. Take a look that it handles at once on load and on resize events, so this div is always in the middle.
您也可以使用相同的策略进行水平对齐。看看它在加载和调整大小事件时立即处理,所以这个 div 总是在中间。
回答by Aman Bansal
You can use that plugin it is very simple to use https://github.com/tenbullstech/jquery-make-me-center
您可以使用该插件使用https://github.com/tenbullstech/jquery-make-me-center非常简单
$("div.box").makemecenter();