Best css questions in April 2012

Is the Gideon Sundback zipper doodle[Google,24th April] completely javascript?

16 votes

Is the Gideon Sundback google doodle implemented in javascript ?

I tried to trace through firebug, but could not really "get" its implementation details ?

Any thoughts on how it might be implemented ?

Yes it's JavaScript.

It uses the <canvas> element.

Here is the code:

(function () {
    var c = !0,
        d = !1;
    try {
        window.google || (window.google = {});
        google.doodle || (google.doodle = {});
        var f = google.doodle,
            h, j, k, l, m, n, o = 0,
            p = 23,
            q, r, s, u, v, w, x, y = 142,
            z = 356,
            A = 311,
            B = 0,
            C = 0,
            D = 30,
            E = 15,
            F = d,
            G, H = d,
            I = d,
            J = {
                back: {
                    src: "/logos/2012/sundback12-hp-s.png",
                    height: 31,
                    width: 24,
                    x: 0,
                    y: 0
                },
                s: {
                    src: "/logos/2012/sundback12-hp-l.jpg",
                    height: 120,
                    width: 186,
                    x: 0,
                    y: 0
                },
                F: {
                    src: "/logos/2012/sundback12-hp-l.jpg",
                    height: 120,
                    width: 186,
                    x: 186,
                    y: 0
                },
                i: {
                    src: "/logos/2012/sundback12-hp-s.png",
                    height: 60,
                    width: 28,
                    x: 24,
                    y: 0
                },
                top: {
                    src: "/logos/2012/sundback12-hp-s.png",
                    height: 23,
                    width: 8,
                    x: 52,
                    y: 0
                },
                G: {
                    src: "/logos/2012/sundback12-hp-s.png",
                    height: 7,
                    width: 15,
                    x: 60,
                    y: 0
                },
                B: {
                    src: "/logos/2012/sundback12-hp-s.png",
                    height: 7,
                    width: 15,
                    x: 75,
                    y: 0
                }
            },
            K = function () {
                google.psy && google.nav && google.nav.go ? google.nav.go("/search?q=Gideon+Sundback&ct=sundback12-hp&oi=ddle") : window.location.href = "/search?q=Gideon+Sundback&ct=sundback12-hp&oi=ddle"
            },
            L = function (a, b, g, i, e) {
                a.beginPath();
                a.moveTo(b, g);
                a.lineTo(i, e);
                a.stroke()
            },
            M = function (a, b, g) {
                var i = document.createElement("canvas"),
                    e = i.getContext("2d"),
                    t = j.createLinearGradient(0, 0, 0, g);
                t.addColorStop(0, "#f5f5f5");
                t.addColorStop(1, "#f1f1f1");
                e.fillStyle = t;
                e.fillRect(1, 1, b - 2, g - 2);
                e.lineWidth = 1;
                e.strokeStyle = "#d0d0d0";
                L(e, 1, 0, b - 1, 0);
                L(e, b, 1, b, g - 1);
                L(e, b - 1, g, 1, g);
                L(e, 0, g - 1, 0, 1);
                e.fillStyle = "#444";
                e.textAlign = "center";
                e.font = "bold 11px Arial,sans-serif";
                e.fillText(a, b / 2, g * 2 / 3);
                return i
            },
            N = function (a, b) {
                var g = document.createElement("canvas"),
                    i = g.getContext("2d");
                i.fillStyle = "#fff";
                i.fillRect(0, 0, b, 29);
                i.lineWidth = 1;
                i.strokeStyle = "#c0c0c0";
                L(i, 0, 0, b, 0);
                i.strokeStyle = "#d9d9d9";
                L(i, 0, 29, b, 29);
                var e = a ? 0 : b;
                L(i, e, 0, e, 29);
                return g
            },
            O = "move,-ie-grabbing,-moz-grabbing,-o-grabbing,-webkit-grabbing,grabbing".split(","),
            aa = "move,-ie-grab,-moz-grab,-o-grab,-webkit-grab,grab".split(","),
            P = function (a, b) {
                if (a) for (var g in b) a.style.cursor = b[g]
            },
            ba = function (a) {
                if (!H && !Q()) {
                    F = H = c;
                    google.listen(window, "mouseup", R);
                    google.listen(window, "mousemove", S);
                    h.style.zIndex = "2000";
                    P(h, O);
                    k && P(k, O);
                    l.q.blur();
                    google.psy && K();
                    T();
                    S(a)
                }
            },
            R = function () {
                if (!I && H) {
                    I = c;
                    F = d;
                    h.style.cursor = "auto";
                    if (k) k.style.cursor = "auto";
                    ca()
                }
            },
            S = function (a) {
                if (F) {
                    a ? a.stopPropagation && a.stopPropagation() : window.event.cancelBubble = c;
                    a.preventDefault ? a.preventDefault() : a.returnValue = d;
                    a = a || window.event;
                    G = !a ? [0, 0] : [(a.clientX || a.targetTouches && a.targetTouches[0] && a.targetTouches[0].clientX || 0) + (document.body.scrollLeft || document.documentElement.scrollLeft || 0), (a.clientY || a.targetTouches && a.targetTouches[0] && a.targetTouches[0].clientY || 0) + (document.body.scrollTop || document.documentElement.scrollTop || 0)];
                    a = B;
                    B = Math.max(0, G[1] - o - 30 - J.i.height);
                    if (f.z > 0) {
                        f.z--;
                        var b = B - a;
                        Math.abs(b) > 50 && (B = a + b * 0.25)
                    }
                    U()
                }
            },
            T = function () {
                var a = document.getElementById("mgmhppd");
                o = a ? a.offsetHeight : 0;
                a = o + 30;
                h.style.top = a + "px";
                var b = document.getElementById("ftby");
                if (b && b.parentNode) p = b.parentNode.offsetHeight;
                h.height = x = document.body.clientHeight - (o + (H ? 0 : 30 + p));
                var b = 833,
                    g = document.getElementById("gbqf");
                g && (b = Math.max(b, g.offsetWidth));
                h.width = v = Math.max(b, document.body.clientWidth);
                w = v / 2;
                G || (G = [0, 0]);
                G[0] = w;
                if (k) {
                    b = k.style;
                    b.top = h.style.top;
                    b.left = w - 236 + "px";
                    if (l) b.height = google.style.getPageOffsetTop(l) - a + "px"
                }
                da();
                U()
            },
            V = function (a) {
                a.addColorStop(0, "rgba(255,255,255,0)");
                a.addColorStop(0.01, "#eee");
                a.addColorStop(0.55, "#fff");
                a.addColorStop(0.58, "#b1b1b1");
                a.addColorStop(0.68, "#dedede");
                a.addColorStop(0.98, "#dedede");
                a.addColorStop(0.99, "rgba(255,255,255,0)")
            },
            da = function () {
                q = w - C + 1;
                r = w + C;
                s = q - 42;
                u = r + 42
            },
            U = function () {
                if (j) {
                    j.clearRect(0, 0, v, x);
                    var a = s - B,
                        b = u + B;
                    j.fillStyle = "#fff";
                    f.g || j.fillRect(0, 0, v, x);
                    j.beginPath();
                    j.moveTo(0, 0);
                    j.lineTo(a, 0);
                    j.arc(a, B, B + 21, -Math.PI / 2, 0, d);
                    j.lineTo(s, x);
                    j.lineTo(0, x);
                    j.lineTo(0, 0);
                    j.fill();
                    j.beginPath();
                    j.moveTo(v, 0);
                    j.lineTo(b, 0);
                    j.arc(b, B, B + 21, -Math.PI / 2, Math.PI, c);
                    j.lineTo(u, x);
                    j.lineTo(v, x);
                    j.lineTo(v, 0);
                    j.fill();
                    W(J.s, -42, y, c);
                    W(J.F, -42, y, d);
                    if (H) {
                        W(J.v, 0, A, c);
                        W(J.w, 0, A, d)
                    }
                    if (H) {
                        var g = !l || l.q.dir != "rtl";
                        W(J.search, -57, z, g);
                        W(J.C, -57, z, !g)
                    }
                    g = j.createRadialGradient(a, B, B, a, B, B + 42);
                    V(g);
                    j.fillStyle = g;
                    j.fillRect(a, 0, B + 42, B);
                    a = j.createRadialGradient(b, B, B, b, B, B + 42);
                    V(a);
                    j.fillStyle = a;
                    j.fillRect(r, 0, B + 42, B);
                    a = j.createLinearGradient(s, 0, q, 0);
                    V(a);
                    j.fillStyle = a;
                    j.fillRect(s, B, 42, x - B);
                    a = j.createLinearGradient(u, 0, r, 0);
                    V(a);
                    j.fillStyle = a;
                    j.fillRect(r, B, 42, x - B);
                    a = J.B.height + 5;
                    for (b = 0; b < x; b = b + a) {
                        W(J.G, 3, b + a / 2, c);
                        W(J.B, 3, b, d)
                    }
                    a = A - 50;
                    a = Math.min(1, (a - (B - 50)) / a);
                    if (H && a > 0) {
                        j.save();
                        j.globalAlpha = a;
                        W(J.v, 0, A, c);
                        W(J.w, 0, A, d);
                        j.restore()
                    }
                    X(J.back, r - J.back.width / 2, B);
                    j.save();
                    a = 0;
                    G && (a = Math.atan((w - G[0]) / J.i.height));
                    j.translate(r + a * 6, B + 12 + Math.abs(a) * 6);
                    j.rotate(a);
                    X(J.i, 0 - J.i.width / 2, 0);
                    j.restore();
                    X(J.top, r - J.top.width / 2, B + 5)
                }
            },
            X = function (a, b, g) {
                b > h.width || g > h.height || j.drawImage(a.a, a.x, a.y, a.width, a.height, b, g, a.width, a.height)
            },
            W = function (a, b, g, i) {
                var e = i ? q : r;
                if (g > B) {
                    e = i ? e + b - a.width : e - b;
                    X(a, e, g)
                } else {
                    var t = 0;
                    B != 0 && (t = (B - g) / B);
                    b = B + 42 + b;
                    if (i) {
                        b = b - a.width;
                        e = e - 42 - B + Math.cos(t) * b
                    } else e = e + 42 + B - Math.cos(t) * b;
                    j.save();
                    j.translate(e, B - Math.sin(t) * b);
                    j.rotate(Math.PI * 2 + (i ? -t : t));
                    X(a, 0, 0);
                    j.restore()
                }
            },
            ea = function () {
                google.psy || Y()
            },
            Z = function (a) {
                var b = document.getElementById("hplogo-i");
                if (b) b.style.display = a ? "" : "none"
            },
            Y = function (a) {
                window.clearTimeout(f.A);
                if (n && m) n.style.position = m.style.position = "";
                if (h && (!a || !google.psy && google.browser.product.FIREFOX)) h.style.display = "none";
                if (k) k.style.display = "none";
                Z(c);
                google.unlisten(window, "resize", T);
                google.unlisten(window, "mouseup", R);
                google.unlisten(window, "mousemove", S)
            },
            fa = function () {
                if (google.msg) {
                    f.o && google.msg.unlisten(40, f.o);
                    f.o = function () {
                        H || Y();
                        f.g = c;
                        google.msg.unlisten(40, f.o);
                        f.p ? Y() : U();
                        return c
                    };
                    google.msg.listen(40, f.o);
                    f.k && google.msg.unlisten(64, f.k);
                    f.k = function () {
                        T();
                        google.msg.unlisten(64, f.k);
                        return c
                    };
                    google.msg.listen(64, f.k);
                    f.n && google.msg.unlisten(67, f.n);
                    f.n = function () {
                        H || Y();
                        google.msg.unlisten(67, f.n);
                        return c
                    };
                    google.msg.listen(67, f.n)
                }
            },
            Q = function () {
                var a = window.location.href;
                return a.indexOf("#") > -1 && /[^a-z]q=/.test(a) ? c : d
            },
            $ = function () {
                if (!f.D && google.dstr && google.rein) {
                    f.D = c;
                    google.dstr.push(ea);
                    google.rein.push($)
                }
                f.cpDestroy = Y;
                f.cpInit = $;
                a: {
                    for (var a = document.forms, b = ["f", "gs", "tsf", "gbqf"], g = 0, i; i = b[g++];) if (i = a[i]) {
                        l = i;
                        break a
                    }
                    l = null
                }
                m = l.btnK;
                n = l.btnI;
                if (!(a = !l)) if (!(a = !l.q)) if (!(a = l.q.value.length > 0)) if (!(a = Q())) {
                    h = document.getElementById("hplogo-z");
                    if (!h) {
                        h = document.createElement("canvas");
                        document.body.appendChild(h)
                    }
                    if (h.getContext) {
                        j = h.getContext("2d");
                        Z(d);
                        h.id = "hplogo-z";
                        a = h.style;
                        a.left = "0";
                        a.position = "absolute";
                        a.display = "";
                        a.visibility = "";
                        a.zIndex = "-1";
                        if (k = document.getElementById("hplogo-c")) {
                            k.onmouseover = U;
                            k.onmousedown = ba;
                            k.ontouchstart = ba;
                            k.style.display = "";
                            P(k, aa)
                        }
                        a = c
                    } else a = d;
                    a = !a
                }
                if (a) Z(c);
                else {
                    window.clearTimeout(f.A);
                    C = B = 0;
                    E = 15;
                    D = 30;
                    I = H = d;
                    f.g = d;
                    f.p = d;
                    f.z = 5;
                    f.g = d;
                    fa();
                    for (var e in J) {
                        a = J[e];
                        if (a.src) {
                            a.a = new Image;
                            a.a.onload = U;
                            a.a.src = a.src
                        }
                    }
                    if (l && n && m) {
                        J.search = {
                            a: M(m.innerText || m.textContent || m.value, m.offsetWidth, m.offsetHeight),
                            height: m.offsetHeight,
                            width: m.offsetWidth,
                            x: 0,
                            y: 0
                        };
                        J.C = {
                            a: M(n.innerText || n.textContent || n.value, n.offsetWidth, n.offsetHeight),
                            height: n.offsetHeight,
                            width: n.offsetWidth,
                            x: 0,
                            y: 0
                        };
                        e = Math.floor(google.style.getWidth(l.q) / 2);
                        J.v = {
                            a: N(c, e),
                            height: 29,
                            width: e,
                            x: 0,
                            y: 0
                        };
                        J.w = {
                            a: N(d, e),
                            height: 29,
                            width: e,
                            x: 0,
                            y: 0
                        }
                    }
                    google.listen(window, "resize", T);
                    T();
                    y = Math.max(0, google.style.getPageOffsetTop(l) - o - 15 - J.s.height - 30);
                    z = google.style.getPageOffsetTop(m) - o - 30;
                    A = google.style.getPageOffsetTop(l) - o - 30;
                    if (l && n && m) {
                        b = google.style.getWidth(n) - google.style.getWidth(m);
                        a = e = 42;
                        b > 0 ? e = e + b : a = a - b;
                        b = l.q.dir != "rtl";
                        n.style.position = m.style.position = "relative";
                        n.style[b ? "left" : "right"] = e + "px";
                        m.style[b ? "right" : "left"] = a + "px"
                    }
                    U()
                }
            },
            ca = function () {
                B = B + D;
                D = D + 2;
                G[0] = G[0] + (w - G[0]) * 0.3;
                if (B > x) {
                    C = C + E;
                    E = E + 5;
                    da()
                }
                U();
                if (C < w) f.A = window.setTimeout(ca, 30);
                else {
                    G[0] = w;
                    f.p = c;
                    if (google.psy && f.g) Y();
                    else {
                        Y(c);
                        K()
                    }
                }
            };
        google.x ? google.x({
            id: "DOODLE"
        }, $) : $()
    } catch (ga) {
        google.ml(ga, d, {
            cause: "DOODLE"
        })
    };
})();

Different ways of accessing attribute values using javascript

15 votes
document.getElementById('myId').style;

is one way of accessing the style attribute.. Also we can do the same using document.getElementById('myId').getAttribute('style');

What is the difference between these two ways of getting attribute values..And which one is preferable?

In the first example you're not accessing to the style attribute, but to the style property. The property's value can be anything, in case of the style property is an object. In the second example you're accessing to the style attribute of the tag. The attribute's value can be only string.

In case of some attributes there is a mapping between them. So if you set an attribute style on a HTML node, your style property is updated and your style is applied. However, this is not always true: a well known bug in some versions of IE (at least till IE7) is that sort of mapping is broken, so set an attribute is not reflected to the property.

So, if you want set an attribute on a HTML node, you have to use the second one. But if you want to access to the property of your object that represent a HTML node, you have to use the first one.

In case of the style, the first one is strongly recommended.

To make it clear with an example (in modern browsers):

document.body.style.border = "1px solid red";
console.log(document.body.style); // [object CSSStyleDeclaration]
console.log(document.body.getAttribute("style")); // "border: 1px solid red;"

How to use CSS to hide links without href?

Asked on Tue, 17 Apr 2012 by John css
14 votes

Is this a valid CSS rule?

a[href=""] {display:none}

Basically anytime a link has no href, don't show it. If I recall, I think I could do things like input[type="text"]{display:none;}, so why doesn't my empty anchor link display none work?

The a[href=""] would select anchors which have a href attribute set to an empty string, not anchors which have no href attribute.

In order to select anchors which have no href attribute, you need a:not([href]). Note that the :not() pseudo-selector is not supported in IE below 9, but should work in all other modern browsers.

Div with slanted border using CSS3?

13 votes

I'm creating a javascript widget that resizes neighbouring divs, to reveal more of the div's background-image when the user hovers on it. This is simple enough, and working nicely with the divs having straight edges (obviously). However, the bordering edge 'needs' to be slanted.

Is there a simple way using css3 to make a slanted border between 2 DOM elements?

I have come across css3 transformations (namely, skew), and the diagonal border trick (using half colour, half transparency), but neither of these seem to be able to achieve what I need.

The effect I'm trying to achieve is like in this image: diaglonal border between dom elements

Any help appreciated.

You could technically embed your image in a rotated (see CSS3’s transform: rotate(<X>deg)) <div/>, and then rotate the embeded image with a reverse angle.

Alternatively, you could use SVG (with <clipPath>) to achieve this effect. Plus SVG embedded in <object/> tags can use JavaScript, so the responsive part can be part of the ride.

Both JSFiddle are on their way.

EDIT1: CSS Version: http://jsfiddle.net/kU3tu/
EDIT2: SVG Version: http://jsfiddle.net/b2JJK/

When a child element overflows horizontally, why is the right padding of the parent ignored?

12 votes

Given this simple structure:

<div id="parent">
    <div id="child">Lorem ipsum</div>
</div>

with this CSS:

#parent {
    width: 200px;
    height: 200px;
    padding: 20px;
    overflow-x: scroll;
}

#child {
    width: 500px;      
}

Live demo: http://jsfiddle.net/523me/5/

Notice that the parent has a 20px padding and that the child overflows horizontally (because it is wider). If you scroll the parent all the way to the right, you'll see that the child touches the right edge of the parent.

So, the parent should have a right padding, but it is ignored. It seems that when the child has a fixed width, the right padding of the parent does not apply. (Is this specified by a standard? I would love to know. Please let me know if you find anything!)

Is there a way to force the right padding to be applied in this scenario without having to remove any of the elements from the flow (by floating or positioning)?

enter image description here

Screenshot 1 - The right padding is ignored. This is how all current browsers behave.

Screenshot 2 - The right padding applies. This is what I'm trying to accomplish. (Btw, the screenshot is from IE7, which is the only browser which does not ignore the right padding.)

You're suffering from this problem.

I would solve it giving the margin to the child (and not the padding to the parent):

#parent {
    width: 200px;
    height: 200px;
    overflow-x: scroll;
    background: gray;
}

#child {
    width: 500px;
    background: yellow;  
    display: inline-block;
    margin: 20px; 
}

Demo: jsFiddle

float next sibling left of previous sibling

11 votes

I don't know how to or if this can be done with internet explorer 6.

I am trying to float the next sibling to the left of the previous sibling

This is what im doing and it displays correctly with chrome 6 , opera 9 and firefox 1+.

What the issue with IE6 is that the previous (2) is floated to the far right (where it would be best to be beside to next (1) that is on the left side of the page.

 .wrap{float:left;}
 .prev {float:right;}
 .next {float:left;}


 <div class="wrap">
 <div class="prev">previous (2)</div><div class="next">next (1)</div>
 </div>

If it can be done and you know how to do it i will give a bounty of 250 points

Here you go: http://result.dabblet.com/gist/2489753

You can't use floats there, 'cause IE have a nasty bug, where it stretches the container that is floated to left (or is inline-block) if it contains the float: right;.

However, there is a rarely-used property direction, that can be used for such layouts: it's fully cross-browser and you can use it with inline-blocks for the best effect.

So, for your case the code would be this:

.wrap{
    display: inline-block;
    direction: rtl;
    }
.prev,
.next {
    display: inline-block;
    direction: ltr;
    }

But the display: inline-block don't work for IE from the box, so you need to hack it by making it inline but with hasLayout, so add those to IE only in conditional comments:

.wrap,
.prev,
.next {
    display: inline;
    zoom: 1;
    }

That's it!

Step by step:

  1. Make everything inline-blocks, so it would work in inline flow.
  2. Reverse the flow on the wrapper.
  3. Return the flow to the normal ltr mode in the children.
  4. It's done :)

Generate repeating hexagonal pattern with CSS3

9 votes

So, I need to make a repeating hexagonal pattern, using CSS. If images are needed, I can go there, but I'd prefer to just use CSS if possible.

Here's an idea of what I'm trying to create:

enter image description here

Basically, I just need a way to create the hexagonal shapes, and then overlay text/images on top of them. I don't have much code yet, because I'm not really sure where to start. The problem is, I could just use <div>s in the shape of a hexagon like shown in (http://css-tricks.com/examples/ShapesOfCSS/), but then they wouldn't be connecting. I could use a repeating hexagon pattern, but then I wouldn't be able to specify the exact location of the text or images I need in specific shapes. Thanks for any help in advance.

This was a truly amazing question. Thank you for asking it. The great thing is the fact that:

This Fiddle Proves You Can Do It!

The idea came to me almost instantly after reading your question, but took some time to implement. I originally tried getting a single "hex" with a single div and just pseudo elements, but as best I could tell, there was no way to just rotate the background-image (which I needed), so I had to add some extra div elements to get the right/left sides of the hex, so that I could then use the pseudo elements as a means of background-image rotation.

I tested in IE9, FF, and Chrome. Theoretically any browser supporting CSS3 transform it should work in.

Update (added explanation)

I have some time now to post some code explanation, so here goes:

First, hexagons are defined by 30/60 degree relationships and trigonometry, so those will be the key angles involved. Second, we start with a "row" for the hex grid to reside in. We are going to use inline-block for the hexagon display, but we don't want them to accidentally wrap to the next line and ruin the grid, so white-space: nowrap solves that issue. The margin on this row is going to depend on how much space you want between hex's, and some experimentation may be needed to get what you want.

.hexrow {
    white-space: nowrap;
    /*right/left margin set at (( width of child div x sin(30) ) / 2) 
    makes a fairly tight fit; 
    a 3px bottom seems to match*/
    margin: 0 25px 3px;
}

The immediate children of the .hexrow is going to just be div elements that become the basis for the hex shape. The width will drive the horizontal of the top of the hex, the height is derived from that number since all the sides are equal length on a regular hexagon. Again, margin is going to depend on spacing, but this is where the "overlap" of the individual hexagons is going to occur to make the grid look occur. The background-image is defined once, right here. The shift left on it is to accommodate at least the added width for the left side of the hex. Assuming you want centered text, the text-align handles the horizontal (of course) but the line-height that matches the height is going to allow for a vertical centering.

.hexrow > div {
    width: 100px;
    height: 173.2px; /* ( width x cos(30) ) x 2 */
    /* For margin:
    right/left = ( width x sin(30) ) makes no overlap
    right/left = (( width x sin(30) ) / 2) leaves a narrow separation
    */
    margin: 0 25px;
    position: relative;
    background-image: url(http://i.imgur.com/w5tV4.jpg);
    background-position: -50px 0; /* -left position -1 x width x sin(30) */
    background-repeat: no-repeat;
    color: #ffffff;
    text-align: center;
    line-height: 173.2px; /*equals height*/
    display: inline-block;
}

Each odd number hex we are going to shift down in relation to the "row" and each even shift up. The shift calculation ( width x cos(30) / 2 ) is also the same as (height / 4).

.hexrow > div:nth-child(odd) {
    top: 43.3px; /* ( width x cos(30) / 2 ) */
}

.hexrow > div:nth-child(even) {
    top: -44.8px; /* -1 x( ( width x cos(30) / 2) + (hexrow bottom margin / 2)) */
}

We are using 2 child div elements to create the "wings" of the hex. They are sized the same as the main hex rectangle, and then rotated, and pushed "below" the main hex. Background-image is inherited so that the image is the same (of course), because the image in the "wings" is going to be "lined up" to that in the main rectangle. The pseudo elements are used to generate the images, because they need to be "rerotated" back to horizontal (since we rotated the parent div of them to create the "wings").

The :before of the first will translate its background the width of the negative amount equal to the main portion of the hex plus the original background shift of the main hex. The :before of the second will change the origin point of the translation and will shift the main width on the x-axis, and half the height on the y-axis.

.hexrow > div > div:first-of-type {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: -1;
    overflow: hidden;
    background-image: inherit;

    -ms-transform:rotate(60deg); /* IE 9 */
    -moz-transform:rotate(60deg); /* Firefox */
    -webkit-transform:rotate(60deg); /* Safari and Chrome */
    -o-transform:rotate(60deg); /* Opera */
    transform:rotate(60deg);
}

.hexrow > div > div:first-of-type:before {
    content: '';
    position: absolute;
    width: 200px; /* width of main + margin sizing */
    height: 100%;
    background-image: inherit;
    background-position: top left;
    background-repeat: no-repeat;
    bottom: 0;
    left: 0;
    z-index: 1;

    -ms-transform:rotate(-60deg) translate(-150px, 0); /* IE 9 */
    -moz-transform:rotate(-60deg) translate(-150px, 0); /* Firefox */
    -webkit-transform:rotate(-60deg) translate(-150px, 0); /* Safari and Chrome */
    -o-transform:rotate(-60deg) translate(-150px, 0); /* Opera */
    transform:rotate(-60deg) translate(-150px, 0);

    -ms-transform-origin: 0 0; /* IE 9 */
    -webkit-transform-origin: 0 0; /* Safari and Chrome */
    -moz-transform-origin: 0 0; /* Firefox */
    -o-transform-origin: 0 0; /* Opera */
    transform-origin: 0 0;
}

.hexrow > div > div:last-of-type {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: -2;
    overflow: hidden;
    background-image: inherit;

    -ms-transform:rotate(-60deg); /* IE 9 */
    -moz-transform:rotate(-60deg); /* Firefox */
    -webkit-transform:rotate(-60deg); /* Safari and Chrome */
    -o-transform:rotate(-60deg); /* Opera */
    transform:rotate(-60deg);
}

.hexrow > div > div:last-of-type:before {
    content: '';
    position: absolute;
    width: 200px; /* starting width + margin sizing */
    height: 100%;
    background-image: inherit;
    background-position: top left;
    background-repeat: no-repeat;
    bottom: 0;
    left: 0;
    z-index: 1;

    /*translate properties are initial width (100px) and half height (173.2 / 2 = 86.6) */
    -ms-transform:rotate(60deg) translate(100px, 86.6px); /* IE 9 */
    -moz-transform:rotate(60deg) translate(100px, 86.6px); /* Firefox */
    -webkit-transform:rotate(60deg) translate(100px, 86.6px); /* Safari and Chrome */
    -o-transform:rotate(60deg) translate(100px, 86.6px); /* Opera */
    transform:rotate(60deg) translate(100px, 86.6px);

    -ms-transform-origin: 100% 0; /* IE 9 */
    -webkit-transform-origin: 100% 0; /* Safari and Chrome */
    -moz-transform-origin: 100% 0; /* Firefox */
    -o-transform-origin: 100% 0; /* Opera */
    transform-origin: 100% 0;
}

This span houses your text. The line-height is reset to make the lines of text normal, but the vertical-align: middle works since the line-height was larger on the parent. The white-space is reset so it allows wrapping again. The left/right margin can be set to negative to allow the text to go into the "wings" of the hex.

.hexrow > div > span {
    display: inline-block;
    margin: 0 -30px;
    line-height: 1.1;
    vertical-align: middle;
    white-space: normal;
}

You can individual target rows and cells in those rows to change images, or span text settings, or opacity, or accommodate a larger image (to shift it to the place you want), etc. That is what the following do for the second row.

.hexrow:nth-child(2) > div:nth-child(1) {
    background-image: url(http://i.imgur.com/7Un8Y.jpg);
}

.hexrow:nth-child(2) > div:nth-child(1) > span {
    /*change some other settings*/
    margin: 0 -20px;
    color: black;
    font-size: .8em;
    font-weight: bold;
}

.hexrow:nth-child(2) > div:nth-child(2) {
    background-image: url(http://i.imgur.com/jeSPg.jpg);
}

.hexrow:nth-child(2) > div:nth-child(3) {
    background-image: url(http://i.imgur.com/Jwmxm.jpg);
    /*you can shift a large background image, but it can get complicated
    best to keep the image as the total width (200px) and height (174px)
    that the hex would be.
    */
    background-position: -150px -120px;
    opacity: .3;
    color: black;
}

.hexrow:nth-child(2) > div:nth-child(3) > div:before {
    /*you can shift a large background image, but it can get complicated
    best to keep the image as the total width (200px) and height (174px)
    that the hex would be.
    */
    background-position: -100px -120px; /* the left shift is always less in the pseudo elements by the amount of the base shift */
}

.hexrow:nth-child(2) > div:nth-child(4) {
    background-image: url(http://i.imgur.com/90EkV.jpg);
    background-position: -350px -120px;
}

.hexrow:nth-child(2) > div:nth-child(4) > div:before {
    background-position: -300px -120px;
}

How to switch left and right in a css file?

9 votes

I have an HTML django template page that is both RTL and LTR (depends on user's locale).

The CSS of this page is stored in another file, and that file is currently static.

What is the best way to switch the attribute left and right according to the locale? Is there a built in attribute in CSS for this problem? (I don't want to use JS, it feels too messy)

I have:

.elem{
    left: 10px; 
    bottom: 10px;
    position: absolute;
}

I want something like this:

.elem{
    right-or-left-according-to-html-dir: 10px; 
    bottom: 10px;
    position: absolute;
}

Currently the only option I can think of is turning the file into a template also:

.elem{
    {{dir}}: 10px; 
    bottom: 10px;
    position: absolute;
}

Is there a better way that will let me keep my CSS file static?

You say you're making the document rtl or ltr depending on locale. In that case you can use the :lang() selector to make certain parts of your document have styling depending on the locale.

If you want a little more support (IE7+) you could use the attribute selector selector[lang='en'] though that will only test the attribute on the specified selector.

If you specify the language in the html element (which you should, with lang="en" for example) you can just put the html selector in front of the class you want to apply in certain locales:

.elem {
    margin: 0 10px 0 0;
    color: blue;
}

html[lang='en'] .elem {
    margin: 0 0 0 10px;
}

Even better, if you specified the dir attribute you can directly use that in css like so:

.elem[dir='rtl'] {
    margin: 0 10px 0 0;
}

Please note that with a class on the body element you will always depend on that class always being there. But the dir and lang attribute can be specified on a more specific scope, like a single div, and still be used in the css along with styles for the 'other' reading directions.

CSS circles without width or height? : Is this possible with pure CSS or not?

8 votes

I can turn a div into a circle like this:

.circle {
 background-color: rgba(0, 0139, 0139, 0.5);
 height: 200px;
 width: 200px;
 -moz-border-radius:50%;
 -webkit-border-radius: 50%;
 border-radius:50%;
}

<div class="circle"></div>
</div>

But i have to specify width height:

I want to display three rows of text in DIV's with "no-wrap" so each of the 3 segments of text have there own line and are not wrapped.

I want to display these in the center of a circle and have the circle expand to fit the lines of text.

The text lines will be pulled from a database via PHP, and will vary in character length.

The problem is the method shown above only works if the width / height is specified.

Is this possible with CSS using only, using percentages or would i need a JS work around.

thanks in advance.

Pure CSS Solution with some caveats

This fiddle demonstrates a solution using only css. It works flawlessly (I think) in modern browsers (IE9+, which is needed for border-radius anyway) with single lines of text. Caveats are:

  1. As you can see by the pink "circle" the text must all be contained in a single element (not multiple spans as in the pink). That is not a big problem.
  2. To get any kind of "padding" one needs to put a transparent border on the span set to the "padding" size. This should also not normally be a big issue, since it is unlikely you would want borders inside the circle.
  3. As you can see by the css on the cyan circle, if multiple lines of text are expected (or forced in my case by a max-width), then css for margin-top and top properties must be set according to the number of text lines. This could be an issue depending on application. On the stacked version, IE9 needed overflow: auto set to get it to size correctly.
  4. As you can see by the red circle if you narrow the display area, if white-space: nowrap is not set and a circle begins wrapping its single line of text, then some ovular distortion of the circle occurs.

Each web designer would have to determine if the limitations of this solution can be accounted for or not. If not, then the javascript solution posted here by rgthree should work well. But if only a single line (or some set number of lines, like in my cyan circle) are expected, then this css solution should work well.

How i can display the output of a rss feed in HTML format in a TWebBrowser?

8 votes

I Want to show the output of a rss feed in a formatted HTML in a TWebBrowser component, if a load this feed http://code.google.com/feeds/p/v8/svnchanges/basic in a TWebbrowser, this shows the content as a XML file

enter image description here

but if I use IE to load the same page

enter image description here

I tried injecting a css to the loaded IHTMLDocument2 as is suggested in this question CSS and TWebbrowser delphi but i still getting the same result.

The question is, how i can load the rss feed in TWebbrowser but showing the output as HTML document like IE does?

Just a guess, but you might try applying the following XSL stylesheet (taken from http://snippets.dzone.com/posts/show/1162 and modified as suggested by cherdt in the comments below):

<xsl:stylesheet version="1.0"
  xmlns:atom="http://www.w3.org/2005/Atom"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:dc="http://purl.org/dc/elements/1.1/">
    <xsl:output method="html"/>
    <xsl:template match="/">
    <xsl:apply-templates select="/atom:feed/atom:head"/>
        <xsl:apply-templates select="/atom:feed"/>
    </xsl:template>
    <xsl:template match="atom:feed/atom:head">
        <h3><xsl:value-of select="atom:title"/></h3>
        <xsl:if test="atom:tagline"><p><xsl:value-of select="atom:tagline"/></p></xsl:if>
        <xsl:if test="atom:subtitle"><p><xsl:value-of select="atom:subtitle"/></p></xsl:if>
    </xsl:template>
    <xsl:template match="/atom:feed">
        <h3><xsl:value-of select="atom:title"/></h3>
        <xsl:if test="atom:tagline"><p><xsl:value-of select="atom:tagline"/></p></xsl:if>
        <xsl:if test="atom:subtitle"><p><xsl:value-of select="atom:subtitle"/></p></xsl:if>
        <ul>
            <xsl:apply-templates select="atom:entry"/>
        </ul>
    </xsl:template>
    <xsl:template match="atom:entry">
        <li>
            <a href="{atom:link[@rel='related']/@href}" title="{substring(atom:published, 0, 11)}"><xsl:value-of select="atom:title"/></a>
            <xsl:choose>
                <xsl:when test="atom:content != ''">
                    <p><xsl:value-of select="atom:content" disable-output-escaping="yes" /></p>
                </xsl:when>
                <xsl:otherwise>
                    <p><xsl:value-of select="atom:summary" disable-output-escaping="yes" /></p>
                </xsl:otherwise>
            </xsl:choose>
        </li>
    </xsl:template>
</xsl:stylesheet>

To the feed you are receiving. To transform the document, refer to this question's selected answer and then you could try to assign the resulting XML to the WebBrowser.

I am guessing that you are pointing your WebBrowser control to the feed, but using this approach you would need to download the feed using, for example, Indy (check out TIdHTTP and its Get() method), transform it, and then display in your control.

Please note that the above is just a guess, but I believe it is a good assumption. :)

IE8 Compatibility Mode Asp.net Menu Padding issue

6 votes

Im having an issue with an ASP.net vertical menu, where in certain IE8 modes and other IE browsers, it changes my menu item to have an extra space at the bottom of each menu item, as shown below.

(bad on left, good on right). this is only IE.

bad ___________ good

i did a margin: -1px; for bottom and top and got the following and still adds the space, as shown below.

enter image description here

here is my CSS:

 .SideStaticMenuStyle a, 
 .SideStaticMenuStyle a:visited,
 .SideStaticMenuStyle a:active
 {
    color: #000000;     
    text-decoration: none;
    font-weight: normal;
    font-family: verdana;
    font-size: 12px;
    white-space:normal;
 }
 .SideStaticMenuStyle a:hover 
{
    color: #ffffff;     
    text-decoration: none;
    font-size: 12px;        
    font-weight: normal;
    font-family:  verdana;
 }

 .SideStaticMenuStyle td
 {
    background-color: #c2d0e9;
    width: 160px;
    line-height:14px;
 }

 .SideStaticSelectedStyle td,
 .SideStaticSelectedStyle a, 
 .SideStaticSelectedStyle a:visited,
 .SideStaticSelectedStyle a:active,
 .SideStaticSelectedStyle a:hover
 {
color: #ffffff;     
text-decoration: none;
font-weight: bold;
font-family: verdana;
font-size: 11px;
white-space:normal;
background-color: #6C85B0;
 }

 .SideStaticHoverStyle td
 {
    font-weight: normal;
    font-family:  verdana;
    background-color: #6c85b0;
    color: #ffffff;
}
 .SideStaticHoverStyle td:hover a 
 {
           color: #ffffff;
      }

 .SideStaticMenuItemStyle
 {
    font-weight: normal;
    font-family:  verdana;
    border-bottom: solid 1px #012754;
    border-left: solid 1px #012754;
    border-right: solid 1px #012754;
     border-collapse:collapse;
 }
 .SideStaticMenuItemStyle td
 {      
    padding: 2px 2px 2px 3px;
    text-align: left;
    font-weight: normal;
    font-family:  verdana;
  }
 .SideStaticHoverStyle
 {
    font-weight: normal;
    font-family: verdana;
 }

Here is my HTML:

<asp:Menu ID="Menu2" runat="server"  Orientation="Vertical" ItemWrap="true">
            <DataBindings>
                <asp:MenuItemBinding DataMember="MenuItem" TextField="Title" NavigateUrlField="URL" />
            </DataBindings>
            <StaticMenuStyle CssClass="SideStaticMenuStyle" />
            <StaticSelectedStyle CssClass="SideStaticSelectedStyle" ItemSpacing="0px" />
            <StaticMenuItemStyle CssClass="SideStaticMenuItemStyle" ItemSpacing="0px" />
            <DynamicHoverStyle CssClass="SideDynamicHoverStyle" />
            <DynamicMenuStyle CssClass="SideDynamicMenuStyle" />
            <DynamicSelectedStyle CssClass="SideDynamicSelectedStyle" />
            <DynamicMenuItemStyle CssClass="SideDynamicMenuItemStyle" />
            <StaticHoverStyle CssClass="SideStaticHoverStyle" />
        </asp:Menu>

Page Generate Code:

   <table id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2" class="SideStaticMenuStyle ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_5 ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_2" cellpadding="0" cellspacing="0" border="0">
    <tr onmouseover="Menu_HoverStatic(this)" onmouseout="Menu_Unhover(this)" onkeyup="Menu_Key(this)" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2n1">
        <td><table class="SideStaticMenuItemStyle ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_4" cellpadding="0" cellspacing="0" border="0" width="100%">
            <tr>
                <td style="width:100%;"><a class="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_1 SideStaticMenuItemStyle ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_3" href="servicelink.aspx" target="_self" style="border-style:none;font-size:1em;">ServiceLink</a></td>
            </tr>
        </table></td>
    </tr><tr style="height:0px;">
        <td></td>
    </tr><tr style="height:0px;">
        <td></td>
    </tr><tr onmouseover="Menu_HoverStatic(this)" onmouseout="Menu_Unhover(this)" onkeyup="Menu_Key(this)" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2n2">
        <td><table class="SideStaticMenuItemStyle ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_4" cellpadding="0" cellspacing="0" border="0" width="100%">
            <tr>
                <td style="width:100%;"><a class="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_1 SideStaticMenuItemStyle ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_3" href="fnpc.aspx" target="_self" style="border-style:none;font-size:1em;">Fidelity National Property and Casualty</a></td>
            </tr>
        </table></td>
    </tr><tr style="height:0px;">
        <td></td>
    </tr><tr style="height:0px;">
        <td></td>
    </tr><tr onmouseover="Menu_HoverStatic(this)" onmouseout="Menu_Unhover(this)" onkeyup="Menu_Key(this)" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2n3">
        <td><table class="SideStaticMenuItemStyle ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_4" cellpadding="0" cellspacing="0" border="0" width="100%">
            <tr>
                <td style="width:100%;"><a class="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_1 SideStaticMenuItemStyle ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_3" href="ceridiancorp.aspx" target="_self" style="border-style:none;font-size:1em;">Ceridian Corporation</a></td>
            </tr>
        </table></td>
    </tr><tr style="height:0px;">
        <td></td>
    </tr><tr style="height:0px;">
        <td></td>
    </tr><tr onmouseover="Menu_HoverStatic(this)" onmouseout="Menu_Unhover(this)" onkeyup="Menu_Key(this)" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2n4">
        <td><table class="SideStaticMenuItemStyle ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_4" cellpadding="0" cellspacing="0" border="0" width="100%">
            <tr>
                <td style="width:100%;"><a class="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_1 SideStaticMenuItemStyle ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_3" href="remy.aspx" target="_self" style="border-style:none;font-size:1em;">Remy International, Inc.</a></td>
            </tr>
        </table></td>
    </tr><tr style="height:0px;">
        <td></td>
    </tr><tr style="height:0px;">
        <td></td>
    </tr><tr onmouseover="Menu_HoverStatic(this)" onmouseout="Menu_Unhover(this)" onkeyup="Menu_Key(this)" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2n5">
        <td><table class="SideStaticMenuItemStyle ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_4" cellpadding="0" cellspacing="0" border="0" width="100%">
            <tr>
                <td style="width:100%;"><a class="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_1 SideStaticMenuItemStyle ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_3" href="abrh.aspx" target="_self" style="border-style:none;font-size:1em;">American Blue Ribbon Holdings, LLC</a></td>
            </tr>
        </table></td>
    </tr><tr style="height:0px;">
        <td></td>
    </tr><tr style="height:0px;">
        <td></td>
    </tr><tr onmouseover="Menu_HoverStatic(this)" onmouseout="Menu_Unhover(this)" onkeyup="Menu_Key(this)" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2n6">
        <td><table class="SideStaticMenuItemStyle ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_4" cellpadding="0" cellspacing="0" border="0" width="100%">
            <tr>
                <td style="width:100%;"><a class="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_1 SideStaticMenuItemStyle ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_3" href="cascade.aspx" target="_self" style="border-style:none;font-size:1em;">Cascade Timberlands</a></td>
            </tr>
        </table></td>
    </tr><tr style="height:0px;">
        <td></td>
    </tr>
</table><a id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl00_Menu2_SkipLink"></a>
    </td>

The problem is in the markup of your <asp:Menu /> control. ItemSpacing="0" on the <StaticMenuItemStyle /> is what creates those extra <tr /> tags. Remove it and they will be gone:

<asp:Menu ID="Menu2" runat="server"  Orientation="Vertical" ItemWrap="true">
    <DataBindings>
        <asp:MenuItemBinding DataMember="MenuItem" TextField="Title" NavigateUrlField="URL" />
    </DataBindings>
    <StaticMenuStyle CssClass="SideStaticMenuStyle" />
    <StaticSelectedStyle CssClass="SideStaticSelectedStyle" />
    <StaticMenuItemStyle CssClass="SideStaticMenuItemStyle" />
    <DynamicHoverStyle CssClass="SideDynamicHoverStyle" />
    <DynamicMenuStyle CssClass="SideDynamicMenuStyle" />
    <DynamicSelectedStyle CssClass="SideDynamicSelectedStyle" />
    <DynamicMenuItemStyle CssClass="SideDynamicMenuItemStyle" />
    <StaticHoverStyle CssClass="SideStaticHoverStyle" />
</asp:Menu>

Here's a screen shot of my local machine where I show it fixed:

enter image description here

Draw a line that doesn't get thicker when image stretches

6 votes

Is there a way in SVG to draw a line that keeps thin when the image is stretched?

I'm using a SVG image as a CSS background, something like this:

<svg ... preserveAspectRatio="none" viewBox="0 0 15 15">
  <line x1="0" y1="15" x2="15" y2="0"
        color="#000" stroke="#333" stroke-width="1" />
</svg> 

(A diagonal line). I'm stretching this image through a rectangular element, and when the element is bigger, the line gets thicker, but I need an always-thin line.

Possible? Something like "thin" lines in flash.

In browsers that implement SVG 1.2T you can have a non-scaling stroke As far as I know only Opera supports this currently.

<!-- via property -->
<line … vector-effect="non-scaling-stroke" />

<!-- via CSS -->
<style>
  line { vector-effect:non-scaling-stroke }
</style>
<line … />

Should I use single or double colon notation for pseudo-element css

6 votes

Since IE7 doesn't support the double-colon notation (e.g. ::after) and since modern browsers support the single-colon notation (e.g. :after) for backwards compatibility, should I use solely the single-colon notation and when IE7's market share drops to a negligible level go back and find/replace in my code base? Or should I include both:

.foo:after,
.foo::after { /\*styles\*/ }

Using double alone seems silly if I care about IE7 users (the poor dears).

Do not use both combined with a comma. A CSS 2.1 compliant (not CSS3 capable) user agent will ignore the wohle rule:

When a user agent cannot parse the selector (i.e., it is not valid CSS 2.1), it must ignore the selector and the following declaration block (if any) as well.

CSS 2.1 gives a special meaning to the comma (,) in selectors. However, since it is not known if the comma may acquire other meanings in future updates of CSS, the whole statement should be ignored if there is an error anywhere in the selector, even though the rest of the selector may look reasonable in CSS 2.1.

http://www.w3.org/TR/CSS2/syndata.html#rule-sets

You could however use

.foo:after { /\*styles\*/ }
.foo::after { /\*styles\*/ }

On the other hand this is totally pointless. Just stick with the one-colon notation.

getting fixed height div to continue on next line

6 votes

Not at all sure that this is possible but on the off-chance, here is what I need:

  • 100px high div with top and bottom border.

  • an unknown number of items within the div that are displayed horizontally within the top and bottom borders of the parent div.

  • Importantly, if more items are contained within the div that can fit horizontally, the div should continue with a new row of items below. This second row should also have the items displayed horizontally between the top and bottom borders of the parent div. I do not want the div to simply grow in height and start a new line because this will not allow the top and bottom borders to appear above and below each row of items.

enter image description here

You can set the width of wrapper and put those blocks which are 100px high inside it.

Here is the example: http://jsfiddle.net/BVm5h/

Code:

<div class="wrapper">
 <div class="myClass">1</div>
 <div class="myClass">2</div>
 <div class="myClass">3</div>
 <div class="myClass">4</div>
 <div class="myClass">5</div>
 <div class="myClass">6</div>
 <div class="myClass">7</div>
 <div class="myClass">8</div>
 <div class="myClass">9</div>
 <div class="myClass">10</div>
</div>

CSS:

.wrapper {width: 600px;}

.myClass {
 border-top: 1px solid #FF0000;
 border-bottom: 1px solid #FF0000;
 width: 100px;
 height: 100px;
 float:left;
 margin-top: 5px;
}

div.myClass:last-child {
 width: 100%;
}​

JS:

var no = $('div.myClass').length;
var wlength = $('div.wrapper').width();
var length = $('div.myClass').width();
var tno = no*length;
while(wlength < tno)
 tno=tno-wlength;
var mw = wlength+length-tno;
$('div.myClass').last().css('max-width',mw);

​ ​ By changing the width of wrapper, you can set the number of div blocks you wish in each row.

Edit: Added JS if the last element is to be extended for entire row. ​

Is it harmful to store javascript and css in a database?

5 votes

Ok so I'm trying to store user custom css and javascript in mysql database to be used later the head section on the page, so is it a good idea to store css and javascript in a database ? and if not what is the safe way to do this ?

I'm using wordpress and using esc_js() on javascript code I noticed it adds a backslash before quotes, and adds \n instead of new lines, so is it enough for javascript ?

and thanks in advance.

Short answer: Yes, it's fine as long as it's people you trust.

Long answer:

Make sure you 100% trust your users. There's a lot of exploits that can be done through CSS/JS, so make sure you're only allowing people you completely trust to do this. Even if you tried to implement filtering of some kind, people would find ways around.

Depending on how easily you could figure out the file name, I might consider storing the data in a file. After all, the database is unnecessary overhead if you can readily determine the file name. If you can't determine the file name easily, I just go ahead and store it in the database. (Or if you're planning on storing any meta data or version information or anything, I would go ahead and go for a DB.)