Skip to content

Instantly share code, notes, and snippets.

@cycold
Created May 8, 2014 08:51
Show Gist options
  • Select an option

  • Save cycold/060e48b66288e656d82b to your computer and use it in GitHub Desktop.

Select an option

Save cycold/060e48b66288e656d82b to your computer and use it in GitHub Desktop.
.container{
width:95%;
height:200px;
background: #f90;
margin: 10px auto 0;
position: relative;
}
.box-1{
width:30%;
/* height:30%; */
height:auto;
background: green;
position: absolute;
text-align:center;
}
.box-2{
width:30%;
/* height:30%; */
height:auto;
background: green;
position: absolute;
text-align:center;
}
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script><meta name="description" content="js方法绝定定位元素居中" />
<div class="container">
<div class="box-1">
Lorem ipsum dolor sit amet
dolor sit amet
</div>
</div>
<div class="container">
<div class="box-2">
Lorem ipsum dolor sit amet
dolor sit amet
</div>
</div>
/**
* @author: Suissa
* @name: Absolute Center
* @date: 2007-10-09
*/
/*这个插件是相对于windows窗口的*/
jQuery.fn.center = function() {
return this.each(function(){
var el = $(this);
var h = el.height();
var w = el.width();
var w_box = $(window).width();
var h_box = $(window).height();
var w_total = (w_box - w)/2; //400
var h_total = (h_box - h)/2;
var css = {"position": 'absolute', "left": w_total+"px", "top":
h_total+"px"};
el.css(css);
});
};
$(function(){
$('.box-1').click(function(){
alert(123);
});
$('.box-1').center();
$(window).resize(function(){
$('.box-1').center();
});
});
/*相对于父元素居中对齐*/
jQuery.fn.centerParent = function(parent) {
return this.each(function(){
var el = $(this);
var h = el.height();
var w = el.width();
var w_box = parent.width();
var h_box = parent.height();
var w_total = (w_box - w)/2; //400
var h_total = (h_box - h)/2;
var css = {"position": 'absolute', "left": w_total+"px", "top":
h_total+"px"};
el.css(css);
});
};
$(function(){
var parent = $('.container');
$('.box-2').centerParent(parent);
$(window).resize(function(){
$('.box-2').centerParent(parent);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment