使用 CSS 绘制网格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4191260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Drawing a grid using CSS
提问by lennysan
I'm looking for a way to draw a grid (i.e. http://www.artlex.com/ArtLex/g/images/grid.gif) inside of a div, using CSS (and JS if necessary). It feels like it should be relatively straight forward, but I haven't been able to figure it out. Any advice would be greatly appreciated.
我正在寻找一种在 div 内绘制网格(即http://www.artlex.com/ArtLex/g/images/grid.gif)的方法,使用 CSS(如有必要,还可以使用 JS)。感觉应该是相对简单的,但我一直无法弄清楚。任何建议将不胜感激。
Thank you in advance, Lenny
提前谢谢你,莱尼
回答by user3061127
Here is a simple CSS-only solution, using linear gradients:
这是一个简单的纯 CSS 解决方案,使用线性渐变:
html,
body,
.grid {
height: 100%;
width: 100%;
margin: 0;
}
.grid {
background-image:
repeating-linear-gradient(#ccc 0 1px, transparent 1px 100%),
repeating-linear-gradient(90deg, #ccc 0 1px, transparent 1px 100%);
background-size: 71px 71px;
}
<div class="grid"></div>
回答by Yi Jiang
Here's a simple solution using jQuery. This script will try to fill in as many grid element as possible without overflowing. The function accepts a single parameter, which defines the size of the grid.
这是一个使用 jQuery 的简单解决方案。此脚本将尝试填充尽可能多的网格元素而不会溢出。该函数接受单个参数,该参数定义网格的大小。
function createGrid(size) {
var ratioW = Math.floor($(window).width()/size),
ratioH = Math.floor($(window).height()/size);
var parent = $('<div />', {
class: 'grid',
width: ratioW * size,
height: ratioH * size
}).addClass('grid').appendTo('body');
for (var i = 0; i < ratioH; i++) {
for(var p = 0; p < ratioW; p++){
$('<div />', {
width: size - 1,
height: size - 1
}).appendTo(parent);
}
}
}
It also requires a simple CSS style:
它还需要一个简单的 CSS 样式:
.grid {
border: 1px solid #ccc;
border-width: 1px 0 0 1px;
}
.grid div {
border: 1px solid #ccc;
border-width: 0 1px 1px 0;
float: left;
}
See a simple demo here: http://jsfiddle.net/yijiang/nsYyc/1/
在这里看到一个简单的演示:http: //jsfiddle.net/yijiang/nsYyc/1/
Here's one using native DOM functions. I should also change the initial ratio calculation to use DOM functionsbut I cannot for the life of me get fixed that: window.innerWidth
to return accurate numbers
这是一个使用原生 DOM 函数的方法。我还应该更改初始比率计算以使用 DOM 函数但我一生都无法修正: window.innerWidth
返回准确的数字
function createGrid(size) {
var ratioW = Math.floor((window.innerWidth || document.documentElement.offsetWidth) / size),
ratioH = Math.floor((window.innerHeight || document.documentElement.offsetHeight) / size);
var parent = document.createElement('div');
parent.className = 'grid';
parent.style.width = (ratioW * size) + 'px';
parent.style.height = (ratioH * size) + 'px';
for (var i = 0; i < ratioH; i++) {
for (var p = 0; p < ratioW; p++) {
var cell = document.createElement('div');
cell.style.height = (size - 1) + 'px';
cell.style.width = (size - 1) + 'px';
parent.appendChild(cell);
}
}
document.body.appendChild(parent);
}
createGrid(10);
It's basically a direct translation of the jQuery code. If you need even more performance you can switch to generating the boxes using strings pushed to an array:
它基本上是 jQuery 代码的直接翻译。如果您需要更高的性能,您可以切换到使用推送到数组的字符串来生成框:
arr.push('<div style="width:', (size - 1), 'px;height:', (size - 1), 'px;"></div>');
then at the end
然后在最后
parent.innerHTML = arr.join('');
回答by Gary Chambers
I know this question has already been answered, but I've done considerable work on this exact problem for a project I was working on, so I thought I would share my findings. Rendering speed was a massive issue for me, and like @YiJiang, I started by appending nodes from inside the loop, but I found that this was not a very performant solution, so I looked into ways to optimise the algorithm.
我知道这个问题已经得到了回答,但我已经为我正在从事的项目在这个确切的问题上做了大量工作,所以我想我会分享我的发现。渲染速度对我来说是一个大问题,和@YiJiang 一样,我从循环内部附加节点开始,但我发现这不是一个非常高效的解决方案,所以我研究了优化算法的方法。
Algorithmically speaking, nesting loops causes O(n^2) complexity, which in this case can be avoided by generating the row html once (as it is the same for each row), and then concatenating this string into each row. This results in O(n) complexity, and is by far the most efficient solution I've found.
从算法上讲,嵌套循环会导致 O(n^2) 复杂度,在这种情况下,可以通过生成行 html 一次(因为每行相同),然后将此字符串连接到每行中来避免这种情况。这导致 O(n) 复杂度,并且是迄今为止我发现的最有效的解决方案。
function drawGrid(width, height) {
var grid = '<div id="grid">',
cell_html = '',
i = 0, j = 0;
for( ; i < width; i++) {
cell_html += '<div class="cell"></div>';
}
for( ; j < height; j++) {
grid += '<div class="row">' + cell_html + '</div>';
}
grid += '</div>';
return grid;
}
This creates the basic HTML structure for the grid, which can then be styled appropriately using CSS.
这为网格创建了基本的 HTML 结构,然后可以使用 CSS 对其进行适当的样式设置。
回答by madstop
Here is a solution that is an edited version of @YiJiang's answer to reduce it to O(n) complexity. The only reason I added my solution was that it is complete with css and jsfiddle sample (http://jsfiddle.net/madstop/bM5Kr/)
这是一个解决方案,它是@YiJiang 答案的编辑版本,可将其降低到 O(n) 复杂度。我添加我的解决方案的唯一原因是它带有 css 和 jsfiddle 示例(http://jsfiddle.net/madstop/bM5Kr/)
css:
css:
.gridlines { display: none; position:absolute; background-color:#ccc; }
javascript/jquery:
javascript/jquery:
function createGrid(size) {
var i,
height = $(window).height(),
width = $(window).width(),
ratioW = Math.floor(width/size),
ratioH = Math.floor(height/size);
for (i=0; i<= ratioW; i++) // vertical grid lines
$('<div />').css({
'top': 1,
'left': i * size,
'width': 1,
'height': height })
.addClass('gridlines')
.appendTo('body');
for (i=0; i<= ratioH; i++) // horizontal grid lines
$('<div />').css({
'top': 1 + i * size,
'left': 0,
'width': width,
'height': 1 })
.addClass('gridlines')
.appendTo('body');
$('.gridlines').show();
}
createGrid(50);
回答by Darko Z
This is how i'd do it:
这就是我的做法:
1) Make image of an L where each side of the L is the equal to one of your squares in the grid.
1) 制作 L 的图像,其中 L 的每一边等于网格中的一个正方形。
2) set this as bg image of your div, repeat on x and y axis
2) 将其设置为 div 的 bg 图像,在 x 和 y 轴上重复
3) give your div a 1px black border on the top and right
3) 给你的 div 顶部和右侧一个 1px 的黑色边框
4) you have the desired effect!
4)你有想要的效果!
hope that helps
希望有帮助
Edit after seeing your no images comment:
看到你的无图像评论后编辑:
why not just use a table to make the grid (as you wont be able to do what you want without images) and overlay the table with an absolutely positioned content div?
为什么不只是使用表格来制作网格(因为没有图像您将无法做您想做的事情)并用绝对定位的内容 div 覆盖表格?
回答by John T.
Three years later... @user3061127, I love you!
三年后...@user3061127,我爱你!
The other answers are great, but just using some very simple HTML and CSS yields exactly what I want. A wonderful, beautiful grid. I'd have posted a simple comment with a link to the fiddle, but I'm not cool enough yet, hence my answer instead.
其他答案很好,但仅使用一些非常简单的 HTML 和 CSS 就可以产生我想要的结果。一个美妙的,美丽的网格。我会发布一个带有小提琴链接的简单评论,但我还不够酷,因此我的回答是。
Here's my take based on your original, which gives the two-layered grid look you see on professional graph paper (yes, all this is because I am too stubborn to go out and just buy some!)
这是我根据你的原作的看法,它给出了你在专业方格纸上看到的两层网格外观(是的,这一切都是因为我太固执了,不能出去买一些!)
If you have different sized paper, all you have to do is change the height and width of #main and you're good to go. If you want a different sized grid, all you have to do is change the background-size attributes and the dimensions in the background-image. Note that the repeating background image is finicky. The dimensions have to match up to the background-size or you'll get no repeating lines at all.
如果你有不同尺寸的纸张,你所要做的就是改变#main 的高度和宽度,你就可以开始了。如果你想要一个不同大小的网格,你所要做的就是改变 background-size 属性和 background-image 中的尺寸。请注意,重复的背景图像很挑剔。尺寸必须与背景尺寸相匹配,否则您将根本没有重复的线条。
<!DOCTYPE html>
<html>
<head>
<style>
html, body {
margin: 0;
}
#main {
height: 11in; /* Double this and print at 50% */
position: relative;
width: 8.5in; /* Double this and print at 50% */
}
.grid {
background-image: repeating-linear-gradient(0deg,transparent,transparent 69px,#88F 69px,#88F 70px),
repeating-linear-gradient(-90deg,transparent,transparent 69px,#88F 69px,#88F 70px);
background-size: 70px 70px;
height: 100%;
position: absolute;
width: 100%;
}
.smallgrid {
background-image: repeating-linear-gradient(0deg,transparent,transparent 13px,#CCF 13px,#CCF 14px),
repeating-linear-gradient(-90deg,transparent,transparent 13px,#CCF 13px,#CCF 14px);
background-size: 14px 14px;
height: 100%;
position: absolute;
width: 100%;
}
</style>
</head>
<body>
<div id="main">
<div class="smallgrid"></div>
<div class="grid"></div>
</div>
</body>
</html>
The fiddle: http://jsfiddle.net/ykotfuaw/5/
回答by ashleedawg
"Pure CSS" and exactly 100px2grid.
“纯 CSS”和精确的 100px 2网格。
(A variation of the top-voted answer, above.)
(上面的最高投票答案的变体。)
body { box-sizing:border-box; margin:0; height:100%; width:100%; background-size:100px 100px;
background-image: repeating-linear-gradient(0deg, transparent, transparent 99px, #ccc 99px, #ccc 100px),
repeating-linear-gradient(-90deg, transparent, transparent 99px, #ccc 99px, #ccc 100px);
}