March 26, 2013
CSS Flex Box Layout
前兩天看到了 CSS3 定義了 Flex 的排版方法,玩了一下效果如圖每個方塊的大小會亂數改變,在一個固定寬度的 container 之中排放,如果超出 container 的寬度就自動換行,還能夠指定相反的 order。
不過這個 layout 的 spec 歷經許多重大改變,詳情可以閱讀 W3C Flexbox 或是 MDN 的 Using CSS flexible,話雖如此,現在的 Firefox 仍不支援 flexbox 的換行,上面那張圖我是從 chrome 裡面測試的。
一個簡單的 html
然後一個簡單的 css,主要的功能目前還需要註明 vendor (就是 chrome 用的 webkit)
.element {
min-width: 100px;
min-height: 100px;
margin:10px;
border: 5px;
border-style:solid;
display:-webkit-box;
display:box;
-moz-box-pack:center;
-moz-box-align:center;
-webkit-box-pack:center;
-webkit-box-align:center;
}
#container {
width: 50%;
border: 1px;
border-style:solid;
border-color:#AAA;
display: -webkit-flex;
display: flex;
flex-direction: row;
-webkit-flex-direction: row;
flex-wrap: wrap;
-webkit-flex-wrap: wrap-reverse;
}
js code 也只是產生幾個方塊之後亂數改變大小
'use restrict';
function start(container) {
var nodes,
MAX = 9;
function randomColor() {
// 000000000000 to 000000FFFFFF, it might be 000000FF
var num = '000000' +
(((0xFFFFFF) * Math.random()) | 0).toString(16);
return '#' + num.substring(num.length - 6);
};
function randomInt() {
// -25 ~ 25
return ((Math.random() * 51) | 0) - 25;
};
function Node(i) {
this.elmnt = document.createElement('div');
this.elmnt.className = 'element';
this.elmnt.style.backgroundColor = randomColor();
this.elmnt.style.borderColor = randomColor();
this.elmnt.style.webkitOrder = i;
this.elmnt.textContent = i;
};
Node.prototype.adj = function() {
this.elmnt.style.width = 150 + randomInt();
this.elmnt.style.height = 150 + randomInt();
return this;
};
function init() {
var node,
counter;
nodes = new Array();
for (counter = 0; counter < MAX; counter++) {
node = new Node(counter);
container.appendChild(node.adj().elmnt);
nodes.push(node);
}
};
init();
}
html/js/css 上手之後還挺好玩的,只是現階段的 css 排版真痛苦,CSS3 的功能彷彿看得見吃不到,我覺得 fragment 的情況比 Android 還要慘烈。
Subscribe to:
Post Comments (Atom)


No comments:
Post a Comment