使用 CSS 绘制网格

发布于 2024-10-03 04:45:46 字数 226 浏览 0 评论 0原文

我正在寻找一种绘制网格的方法(即 http://www. artlex.com/ArtLex/g/images/grid.gif)在 div 内,使用 CSS(必要时还可以使用 JS)。感觉应该是比较简单的,但我一直没能弄清楚。任何建议将不胜感激。

先感谢您, 莱尼

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.

Thank you in advance,
Lenny

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

遗失的美好 2024-10-10 04:45:46

这是一个简单的纯 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>

Here is a simple CSS-only solution, using linear gradients:

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>

有深☉意 2024-10-10 04:45:46

这是一个使用 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);
        }
    }
}

它还需要一个简单的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;
}

在这里查看一个简单的演示:http://jsfiddle.net /yijian/nsYyc/1/


这是使用原生 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);

它基本上是直接翻译jQuery 代码。如果您需要更高的性能,您可以切换到使用推送到数组的字符串来生成框:

arr.push('<div style="width:', (size - 1), 'px;height:', (size - 1), 'px;"></div>');

然后在最后

parent.innerHTML = arr.join('');

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.

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:

.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/


Here's one using native DOM functions. I should also change the initial ratio calculation to use DOM functions but I cannot for the life of me get window.innerWidth to return accurate numbers fixed that:

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:

arr.push('<div style="width:', (size - 1), 'px;height:', (size - 1), 'px;"></div>');

then at the end

parent.innerHTML = arr.join('');
情释 2024-10-10 04:45:46

我知道这个问题已经得到了解答,但我已经为我正在从事的项目针对这个确切问题做了相当多的工作,所以我想我会分享我的发现。渲染速度对我来说是一个大问题,就像@YiJiang一样,我首先从循环内部附加节点,但我发现这不是一个非常高性能的解决方案,所以我研究了优化算法的方法。

从算法上来说,嵌套循环会导致 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;
}

这将为网格创建基本的 HTML 结构,然后可以使用 CSS 对其进行适当的样式设置。

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.

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.

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.

土豪我们做朋友吧 2024-10-10 04:45:46

“纯 CSS”和 100px2 网格。

(票数最高的上面的答案的变体。)

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); 
     }

"Pure CSS" and exactly 100px2 grid.

(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); 
     }

扛起拖把扫天下 2024-10-10 04:45:46

这是一个解决方案,它是 @YiJiang 答案的编辑版本,可将其复杂度降低到 O(n) 。我添加解决方案的唯一原因是它包含 css 和 jsfiddle 示例(http://jsfiddle.net/ madstop/bM5Kr/)

css:

.gridlines { display: none; position:absolute; background-color:#ccc; }

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);

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/)

css:

.gridlines { display: none; position:absolute; background-color:#ccc; }

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);
在风中等你 2024-10-10 04:45:46

三年后...@user3061127,我爱你!

其他答案都很好,但仅使用一些非常简单的 HTML 和 CSS 就可以得到我想要的结果。一个美妙、美丽的网格。我本来会发布一条简单的评论,其中包含小提琴的链接,但我还不够酷,因此我的答案。

这是我根据你的原创的看法,它给出了你在专业方格纸上看到的两层网格的外观(是的,这一切都是因为我太固执,不愿意出去买一些!)

如果你有不同尺寸的纸张,所有你所要做的就是改变 #main 的高度和宽度,然后你就可以开始了。如果您想要不同大小的网格,您所要做的就是更改背景大小属性和背景图像中的尺寸。请注意,重复的背景图像很挑剔。尺寸必须与背景尺寸相匹配,否则您将根本不会得到重复的线条。

<!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>

小提琴:
http://jsfiddle.net/ykotfuaw/5/

Three years later... @user3061127, I love you!

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.

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.

<!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/

江南月 2024-10-10 04:45:46

我就是这样做的:

1)制作一个 L 的图像,其中 L 的每一侧都等于网格中的一个正方形。

2) 将其设置为 div 的背景图像,在 x 和 y 轴上重复

3) 在顶部和右侧给你的 div 一个 1px 的黑色边框

4) 你就得到了想要的效果!

有所帮助

希望在看到您的无图像评论后对编辑

:为什么不只使用表格来制作网格(因为没有图像您将无法执行您想要的操作)并用绝对定位的内容 div 覆盖表格?

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.

2) set this as bg image of your div, repeat on x and y axis

3) give your div a 1px black border on the top and right

4) you have the desired effect!

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?

梦亿 2024-10-10 04:45:46

如果有人来寻找网格上的褪色效果,我找到了你:

html, 
body,
.grid {
    height: 100%;
    width: 100%;
    margin: 0;
}

.grid {
    position: relative;
    background-image:
      repeating-linear-gradient(#cccccc66 0 1px, transparent 1px 100%),
      repeating-linear-gradient(90deg, #cccccc66 0 1px, transparent 1px 100%);
    background-size: 8px 8px, 8px 8px; /* Grid size */
}

.grid::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(to bottom, rgba(208, 219, 230, 1.0), rgba(231, 234, 241, 0.75), rgba(228, 232, 239, 0.5));
    pointer-events: none; /* Allow interactions to pass through */
}
<div class="grid"></div>

If anyone ever comes looking for a fading effect on their grid, I got you:

html, 
body,
.grid {
    height: 100%;
    width: 100%;
    margin: 0;
}

.grid {
    position: relative;
    background-image:
      repeating-linear-gradient(#cccccc66 0 1px, transparent 1px 100%),
      repeating-linear-gradient(90deg, #cccccc66 0 1px, transparent 1px 100%);
    background-size: 8px 8px, 8px 8px; /* Grid size */
}

.grid::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(to bottom, rgba(208, 219, 230, 1.0), rgba(231, 234, 241, 0.75), rgba(228, 232, 239, 0.5));
    pointer-events: none; /* Allow interactions to pass through */
}
<div class="grid"></div>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文