好吧,首先,我是新手,所以请温柔一点。我试图布局多列的div。每个div包含多个垂直堆叠的图像。这些图像的大小都是一样的。以下是我使用jQuery编写的代码:
var $columns= $('<div />', {
css: {
align: 'center', position: 'absolute',
height: 125, width: '100%', left: 0, top: 355, zIndex: 10
},
id: 'columns',
text: 'Towers'
}).appendTo('#mainDiv');
for (var c = 0; c < 6; ++c) {
var $c = $('<div />', {
css: {
marginLeft: 5, marginRight: 5,
textAlign: 'center',
top: 20, width: 20, zIndex: 20
},
id: 'c' + c
});
for (var i = 0; i < 8; ++i) {
$c.append($('<img />', {
css: {
marginBottom: 0, zIndex: 30
},
id: 'c' + c + 'i' + i,
src: 'image' + c + '.png'
}));
}
$columns.append($c);
}
每张图片尺寸为17x11px。当我运行这个,我得到6列8图像垂直堆叠。但是,这些列都在一个列中。我要它们并排。这是完全错误的做法吗?或者至少我接近了。
额外的信用:我如何使图像重叠彼此说4px从上到下?
<div>
是一个block元素,所以它默认有display:block
;这意味着除非你给它指定一个特定的宽度,否则它的宽度和它的父元素一样宽。我认为你要做的是使用inline-block
和$c
:
var $c = $('<div />', {
css: {
display: 'inline-block',
marginLeft: 5, marginRight: 5,
textAlign: 'center',
zIndex: 20
},
id: 'c' + c
});
设置top
不会为您做任何事情,因为您没有指定position
。如果图片是17x11,那么你应该这样写:
$c.append($('<img />', {
css: {
marginBottom: 0, zIndex: 30
},
id: 'c' + c + 'i' + i,
src: 'image' + c + '.png',
width: 17,
height: 11
}));
如果你想要一点重叠,然后设置一个负的上边距来推动他们一点,并设置display: block
在图像上。
你的解决方案真奇怪,我真是又喜欢又讨厌。然而,如果没有给你的内部div一个位置属性,它们将默认为static
, top/left不会做任何事情。
另外,CSS定位背后的思想是有一个位置相对的外部元素和位置绝对的内部元素。这些内部元素将具有相对于父div (position:relative)的绝对定位。
var $columns= $('<div />', {
css: {
align: 'center', position: 'relative',
height: 125, width: '100%', left: 0, top: 0, zIndex: 10
},
id: 'columns',
text: 'Towers'
}).appendTo('#mainDiv');
for (var c = 0; c < 6; ++c) {
var $c = $('<div />', {
css: {
marginLeft: 5, marginRight: 5,
textAlign: 'center',
position: 'absolute', top: 20, left:15*c,
width: 20, zIndex: 20
},
id: 'c' + c
});
for (var i = 0; i < 8; ++i) {
$c.append($('<img />', {
css: {
marginBottom: 0, zIndex: 30
},
id: 'c' + c + 'i' + i,
src: 'image' + c + '.png'
}));
}
$columns.append($c);
}
如果你想要图像重叠,你可以在图像上再次使用绝对定位。假设你已经循环遍历了它们:
css: {
marginBottom: 0, zIndex: 30,
position: 'absolute',
left:0, top:15 * i
}