是否有可能在一个div内的两个轴上的图像居中? [英] Is it possible to center an image on both axis inside a div?
问题描述
我得到了一个提示,我可以使用那个after函数。
我有一个脚本,用一个运行jQuery Cycle Lite插件的图像加载到一个div中。插件在每次刷新图像时对图片进行更改。所以我写了:
$(#display div)。css({
margin:0 auto ,
text-align:center,
});
这样构建的html:
< div id =display>
< div id =slideshow1>
< img ... />
< / div>
< / div>
这是行不通的,怎么了?
水平居中,我需要垂直居中)..
编辑:
我有点懂工作,但它仍然需要帮助,任何人知道为什么它的行为怪异?
http://hem.bredband.net/noor/bildspelet.html
感谢@pekka的链接 首先,在JavaScript对象中的尾随逗号是不好的东西,删除最后一个逗号。
其次,您可以像这样计算它:
var $ div = $('#display');
$ div.css('position','relative');
var $ kids = $ div.children();
//我假设你想把所有的幻灯片放在中间?
$ kids.each(function(){
var $ this = $(this);
$ this.css({
left:($ div.innerWidth(true) - $ this.width())/ 2,
top:($ div.innerHeight(true) - $ this.height())/ 2,
position:'absolute'
} );
});
查看您的示例:< div id =display >
需要在css中设置一个高度(甚至是100%),否则它将一直缩小为包含(当所有孩子被定位为绝对位置时,高度将折叠为零)。请查看 jsbin示例
I have a script that loads in a div with images running jQuery Cycle Lite Plugin.
I got the tip that I could us the "after" function in that plugin to make changes to the picture each time the image is refreshed. So I wrote this:
$("#display div").css({
margin: "0 auto",
"text-align": "center",
});
The html built like this:
<div id="display">
<div id="slideshow1">
<img ... />
</div>
</div>
This isn't working, whats wrong?
( this is supposed to center it horizontally, i need to center it vertically to )..
edit:
I kind of got it working but it still needs help, anyone that knows why its acting weird?
http://hem.bredband.net/noor/bildspelet.html
thanks @pekka for the link
First of all, trailing commas in JavaScript objects is bad stuff, remove the last comma.
Second of all you could probably calculate it like so:
var $div = $('#display');
$div.css('position', 'relative');
var $kids = $div.children();
// I'm assuming you want to center all the slideshows?
$kids.each(function() {
var $this = $(this);
$this.css({
left: ($div.innerWidth(true) - $this.width()) / 2,
top: ($div.innerHeight(true) - $this.height()) / 2,
position: 'absolute'
});
});
From looking at your sample: your <div id="display">
needs to have a height set (even 100%) in the css, or it will always shrink to contain (which when all children are made absolute positioning, the height will fold to zero). Please take a look at the jsbin example
这篇关于是否有可能在一个div内的两个轴上的图像居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!