使用jQuery将DIV置于屏幕中心
-
03-07-2019 - |
题
如何使用jQuery在屏幕中心设置<div>
?
解决方案
我喜欢向jQuery添加函数,所以这个函数会有所帮助:
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}
现在我们可以写:
$(element).center();
演示:小提琴(附加参数)
其他提示
我在这里放了一个 jquery插件
非常短的版本
$('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'});
简短版
(function($){
$.fn.extend({
center: function () {
return this.each(function() {
var top = ($(window).height() - $(this).outerHeight()) / 2;
var left = ($(window).width() - $(this).outerWidth()) / 2;
$(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
});
}
});
})(jQuery);
由此代码激活:
$('#mainDiv').center();
PLUGIN VERSION
(function($){
$.fn.extend({
center: function (options) {
var options = $.extend({ // Default values
inside:window, // element, center into window
transition: 0, // millisecond, transition time
minX:0, // pixel, minimum left element value
minY:0, // pixel, minimum top element value
withScrolling:true, // booleen, take care of the scrollbar (scrollTop)
vertical:true, // booleen, center vertical
horizontal:true // booleen, center horizontal
}, options);
return this.each(function() {
var props = {position:'absolute'};
if (options.vertical) {
var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
top = (top > options.minY ? top : options.minY);
$.extend(props, {top: top+'px'});
}
if (options.horizontal) {
var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
left = (left > options.minX ? left : options.minX);
$.extend(props, {left: left+'px'});
}
if (options.transition > 0) $(this).animate(props, options.transition);
else $(this).css(props);
return $(this);
});
}
});
})(jQuery);
由此代码激活:
$(document).ready(function(){
$('#mainDiv').center();
$(window).bind('resize', function() {
$('#mainDiv').center({transition:300});
});
);
是吗?
更新:
来自 CSS-Tricks
.center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%); /* Yep! */
width: 48%;
height: 59%;
}
这是我的目标。我最终将它用于我的Lightbox克隆。此解决方案的主要优点是即使窗口调整大小,元素也会自动保持居中,这使其成为这种用法的理想选择。
$.fn.center = function() {
this.css({
'position': 'fixed',
'left': '50%',
'top': '50%'
});
this.css({
'margin-left': -this.outerWidth() / 2 + 'px',
'margin-top': -this.outerHeight() / 2 + 'px'
});
return this;
}
我正在扩展@TonyL给出的伟大答案。我正在添加Math.abs()来包装值,并且我还考虑到jQuery可能在<!>中;没有冲突<!>模式,例如在WordPress中。
我建议您使用Math.abs()包装顶部和左侧值,如下所示。如果窗口太小,并且您的模态对话框顶部有一个关闭框,这将防止看不到关闭框的问题。托尼的功能可能具有负面价值。关于如何结束负值的一个很好的例子是,如果你有一个大的居中对话框,但最终用户已经安装了几个工具栏和/或增加了他的默认字体 - 在这种情况下,模态对话框上的关闭框(如果在顶部)可能不可见和可点击。
我做的另一件事是通过缓存$(window)对象来加快速度,以便减少额外的DOM遍历,并使用集群CSS。
jQuery.fn.center = function ($) {
var w = $(window);
this.css({
'position':'absolute',
'top':Math.abs(((w.height() - this.outerHeight()) / 2) + w.scrollTop()),
'left':Math.abs(((w.width() - this.outerWidth()) / 2) + w.scrollLeft())
});
return this;
}
要使用,您可以执行以下操作:
jQuery(document).ready(function($){
$('#myelem').center();
});
我会使用 jQuery UI position
功能。
查看工作演示 。
<div id="test" style="position:absolute;background-color:blue;color:white">
test div to center in window
</div>
如果我有一个id为<!>的div; test <!> quot;然后,以下脚本将div放在文档就绪的窗口中。 (位置选项中<!>“我的<!>”和<!>“; <!>”的默认值为<!>“;中心<!>”;
<script type="text/javascript">
$(function(){
$("#test").position({
of: $(window)
});
};
</script>
我想纠正一个问题。
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
以上代码不适用于this.height
(假设用户调整屏幕大小并且内容是动态的)和scrollTop() = 0
,例如:
window.height
是600
650
是-25
600 - 650 = -50
-50 / 2 = -25
现在,该框位于屏幕中心<=>。
如果你想要一个总是位于页面中间的元素,我不认为拥有绝对位置会是最好的。你可能想要一个固定的元素。我找到了另一个使用固定定位的jquery居中插件。它被称为固定中心。
这是未经测试的,但这样的事情应该有效。
var myElement = $('#myElement');
myElement.css({
position: 'absolute',
left: '50%',
'margin-left': 0 - (myElement.width() / 2)
});
此功能的过渡组件在Chrome中对我来说效果不佳(没有在别处测试)。我会调整窗口的大小,我的元素会慢慢地掠过,试图赶上。
所以以下函数注释了这一点。另外,我添加了传入可选x <!>放大器的参数; y booleans,如果你想垂直居中但不是水平居中,例如:
// Center an element on the screen
(function($){
$.fn.extend({
center: function (x,y) {
// var options = $.extend({transition:300, minX:0, minY:0}, options);
return this.each(function() {
if (x == undefined) {
x = true;
}
if (y == undefined) {
y = true;
}
var $this = $(this);
var $window = $(window);
$this.css({
position: "absolute",
});
if (x) {
var left = ($window.width() - $this.outerWidth())/2+$window.scrollLeft();
$this.css('left',left)
}
if (!y == false) {
var top = ($window.height() - $this.outerHeight())/2+$window.scrollTop();
$this.css('top',top);
}
// $(this).animate({
// top: (top > options.minY ? top : options.minY)+'px',
// left: (left > options.minX ? left : options.minX)+'px'
// }, options.transition);
return $(this);
});
}
});
})(jQuery);
要使元素相对于浏览器视口(窗口)居中,请不要使用position: absolute
,正确的位置值应为fixed
(绝对意味着:<!> \ n;元素相对于其第一个位置定位(非静态)祖先元素<!>“;”。
建议的中心插件的替代版本使用<!> quot;%<!>;而不是<!>“; px <!>”;因此,当您调整窗口大小时,内容将保持居中:
$.fn.center = function () {
var heightRatio = ($(window).height() != 0)
? this.outerHeight() / $(window).height() : 1;
var widthRatio = ($(window).width() != 0)
? this.outerWidth() / $(window).width() : 1;
this.css({
position: 'fixed',
margin: 0,
top: (50*(1-heightRatio)) + "%",
left: (50*(1-widthRatio)) + "%"
});
return this;
}
你需要把margin: 0
从宽度/高度中排除内容边距(因为我们使用的是固定位置,边距没有意义)。
根据jQuery doc使用.outerWidth(true)
应该包含边距,但是当我在Chrome中尝试时它没有按预期工作。
50*(1-ratio)
来自:
窗口宽度:W = 100%
元素宽度(以%为单位):w = 100 * elementWidthInPixels/windowWidthInPixels
他们计算中心左侧:
left = W/2 - w/2 = 50 - 50 * elementWidthInPixels/windowWidthInPixels =
= 50 * (1-elementWidthInPixels/windowWidthInPixels)
这很棒。我添加了一个回调函数
center: function (options, callback) {
结果
if (options.transition > 0) {
$(this).animate(props, options.transition, callback);
} else {
$(this).css(props);
if (typeof callback == 'function') { // make sure the callback is a function
callback.call(this); // brings the scope to the callback
}
}
编辑:
如果问题教会了我什么,就是这样:不要改变已经有效的东西:)
我正在提供(几乎)逐字复制的关于如何处理 http://www.jakpsatweb.cz/css/css-vertical-center-solution.html - 它对IE进行了大量攻击,但提供了一种纯粹的CSS方式来回答这个问题:
.container {display:table; height:100%; position:absolute; overflow:hidden; width:100%;}
.helper {#position:absolute; #top:50%;
display:table-cell; vertical-align:middle;}
.content {#position:relative; #top:-50%;
margin:0 auto; width:200px; border:1px solid orange;}
小提琴: http://jsfiddle.net/S9upd/4/
我通过浏览器运行它,看起来很好;如果没有别的,我会保留下面的原文,以便CSS规范所规定的保证金百分比处理看到了光明。
原件:
看起来我迟到了!
上面有一些评论表明这是一个CSS问题 - 关注点和所有问题的分离。让我先说明CSS 真的在这个问题上自我抨击。我的意思是,这样做有多容易:
.container {
position:absolute;
left: 50%;
top: 50%;
overflow:visible;
}
.content {
position:relative;
margin:-50% 50% 50% -50%;
}
右?容器的左上角位于屏幕的中央,带有负边距,内容将神奇地重新出现在页面的绝对中心! http://jsfiddle.net/rJPPc/
错误! 水平定位没问题,但是垂直......哦,我明白了。显然在css中,当以%为单位设置上边距时,该值计算为百分比总是相对的到包含块的宽度。像苹果和橘子!如果你不相信我或Mozilla doco,可以通过调整内容宽度来玩上面的小提琴,并感到惊讶。
现在,由于CSS是我的面包和黄油,我不打算放弃。与此同时,我更喜欢简单的事情,所以我借用了捷克CSS大师并使其成为一个工作小提琴。简而言之,我们创建了一个表格,其中vertical-align设置为middle:
<table class="super-centered"><tr><td>
<div class="content">
<p>I am centered like a boss!</p>
</div>
</td></tr></table>
而且内容的位置经过精心调整,有良好的旧保证金:0自动; :
.super-centered {position:absolute; width:100%;height:100%;vertical-align:middle;}
.content {margin:0 auto;width:200px;}
承诺的工作小提琴: http://jsfiddle.net/teDQ2/
我这里有一个<!> quot; center <!> quot;确保您尝试居中的元素的方法不仅仅是<!> quot; fixed <!> quot;或<!> quot;绝对<!>;定位,但它也确保你居中的元素小于其父元素,这个中心和元素相对于父元素,如果元素父元素小于元素本身,它会将DOM掠夺到下一个父元素,并且以此为中心。
$.fn.center = function () {
/// <summary>Centers a Fixed or Absolute positioned element relative to its parent</summary>
var element = $(this),
elementPos = element.css('position'),
elementParent = $(element.parent()),
elementWidth = element.outerWidth(),
parentWidth = elementParent.width();
if (parentWidth <= elementWidth) {
elementParent = $(elementParent.parent());
parentWidth = elementParent.width();
}
if (elementPos === "absolute" || elementPos === "fixed") {
element.css('right', (parentWidth / 2) - elementWidth / 2 + 'px');
}
};
我用这个:
$(function() {
$('#divId').css({
'left' : '50%',
'top' : '50%',
'position' : 'absolute',
'margin-left' : -$('#divId').outerWidth()/2,
'margin-top' : -$('#divId').outerHeight()/2
});
});
请使用此:
$(window).resize(function(){
$('.className').css({
position:'absolute',
left: ($(window).width() - $('.className').outerWidth())/2,
top: ($(window).height() - $('.className').outerHeight())/2
});
});
// To initially run the function:
$(window).resize();
你正在进行那种糟糕的转换,因为每次滚动文档时你都会调整元素的位置。你想要的是使用固定定位。我尝试了上面列出的固定中心插件,这似乎很好地解决了这个问题。固定定位允许您将元素居中一次,每次滚动时CSS属性都会为您保留该位置。
这是我的版本。在看了这些例子后,我可能会改变它。
$.fn.pixels = function(property){
return parseInt(this.css(property));
};
$.fn.center = function(){
var w = $($w);
return this.each(function(){
$(this).css("position","absolute");
$(this).css("top",((w.height() - $(this).height()) / 2) - (($(this).pixels('padding-top') + $(this).pixels('padding-bottom')) / 2) + w.scrollTop() + "px");
$(this).css("left",((w.width() - $(this).width()) / 2) - (($(this).pixels('padding-left') + $(this).pixels('padding-right')) / 2) + w.scrollLeft() + "px");
});
};
不需要jquery这个
我用它来居中Div元素。 Css风格,
.black_overlay{
display: none;
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
.white_content {
display: none;
position: absolute;
top: 25%;
left: 25%;
width: 50%;
height: 50%;
padding: 16px;
border: 16px solid orange;
background-color: white;
z-index:1002;
overflow: auto;
}
打开元素
$(document).ready(function(){
$(".open").click(function(e){
$(".black_overlay").fadeIn(200);
});
});
我对TONY L'S ANSWER的更新
这是他现在虔诚使用的答案的修改版本。我想我会分享它,因为它为你可能遇到的各种情况增加了更多的功能,例如不同类型的position
或只想要水平/垂直居中而不是两者。
center.js:
// We add a pos parameter so we can specify which position type we want
// Center it both horizontally and vertically (dead center)
jQuery.fn.center = function (pos) {
this.css("position", pos);
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}
// Center it horizontally only
jQuery.fn.centerHor = function (pos) {
this.css("position", pos);
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}
// Center it vertically only
jQuery.fn.centerVer = function (pos) {
this.css("position", pos);
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
return this;
}
在我的<head>
:
<script src="scripts/center.js"></script>
用法示例:
$("#example1").centerHor("absolute")
$("#example2").centerHor("fixed")
$("#example3").centerVer("absolute")
$("#example4").centerVer("fixed")
$("#example5").center("absolute")
$("#example6").center("fixed")
它适用于任何定位类型,可以轻松地在整个站点中使用,也可以轻松移植到您创建的任何其他站点。没有更令人讨厌的解决方法来正确地集中内容。
希望这对那里的人有用!享受。
很多方法可以做到这一点。我的对象隐藏在BODY标记内的 display:none ,以便定位相对于BODY。使用 $(<!> quot; #object_id <!>;;。show()后,我调用 $(<!> quot; #object_id <!> quot;)。中心()强>
我使用 position:absolute ,因为特别是在小型移动设备上,模态窗口大于设备窗口是可能的,在这种情况下,某些模态内容可能无法访问定位是固定的。
根据其他人的答案和我的具体需求,这是我的口味:
$.fn.center = function () {
this.css("position","absolute");
//use % so that modal window will adjust with browser resizing
this.css("top","50%");
this.css("left","50%");
//use negative margin to center
this.css("margin-left",(-1*this.outerWidth()/2)+($(window).scrollLeft())+"px");
this.css("margin-top",(-1*this.outerHeight()/2)+($(window).scrollTop())+"px");
//catch cases where object would be offscreen
if(this.offset().top<0)this.css({"top":"5px","margin-top":"0"});
if(this.offset().left<0)this.css({"left":"5px","margin-left":"0"});
return this;
};
通常,我只会用CSS做这个...但是因为你问了一个用jQuery做的方法......
以下代码在其容器内水平和垂直居中div:
$("#target").addClass("centered-content")
.wrap("<div class='center-outer-container'></div>")
.wrap("<div class='center-inner-container'></div>");
body {
margin : 0;
background: #ccc;
}
.center-outer-container {
position : absolute;
display: table;
width: 100%;
height: 100%;
}
.center-inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<div id="target">Center this!</div>
(另请参阅 此小提琴 )
CSS解决方案 仅限两行
它可以水平和垂直地集中你的内部div。
#outer{
display: flex;
}
#inner{
margin: auto;
}
仅用于水平对齐,更改
margin: 0 auto;
和垂直,改变
margin: auto 0;
为什么不使用CSS来居中div?
#timer_wrap{
position: fixed;
left: 50%;
top: 50%;
}