draw diagonal lines in div background with CSS

Ing. Michal Hudak picture Ing. Michal Hudak · Aug 2, 2013 · Viewed 175.8k times · Source

I have a div for a preview box:

HTML:

<div class="preview-content">PREVIEW</div>

CSS:

.preview-content {
    background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAGklEQVQIW2NkYGD4D8SMQAwGcAY2AbBKDBUAVuYCBQPd34sAAAAASUVORK5CYII=) repeat;
    width: 100%;
    min-height: 300px;
    max-height: 300px;
    line-height: 300px;
    text-align: center;
    vertical-align: middle;
     font-size: 2em;
}

Question: how to add diagonal lines to div background like in the picture?

note: with CSS only if possible

preview

Thank you in advance.

Answer

RobertT picture RobertT · Nov 8, 2013

Almost perfect solution, that automatically scales to dimensions of an element would be usage of CSS3 linear-gradient connected with calc() as shown below. Main drawback is of course compatibility. Code below works in Firefox 25 and Explorer 10 and 11, but in Chrome (I've tested v30 and v32 dev) there are some subtle problems with lines disappearing if they are too narrow. Moreover disappearing depends on the box dimensions – style below works for div { width: 100px; height: 100px}, but fails for div { width: 200px; height: 200px} for which in my tests 0.8px in calculations needs to be replaced with at least 1.1048507095px for diagonals to be shown and even then line rendering quality is quite poor. Let's hope this Chrome bug will be solved soon.

.crossed {
     background: 
         linear-gradient(to top left,
             rgba(0,0,0,0) 0%,
             rgba(0,0,0,0) calc(50% - 0.8px),
             rgba(0,0,0,1) 50%,
             rgba(0,0,0,0) calc(50% + 0.8px),
             rgba(0,0,0,0) 100%),
         linear-gradient(to top right,
             rgba(0,0,0,0) 0%,
             rgba(0,0,0,0) calc(50% - 0.8px),
             rgba(0,0,0,1) 50%,
             rgba(0,0,0,0) calc(50% + 0.8px),
             rgba(0,0,0,0) 100%);
}
<textarea class="crossed"></textarea>