Search code examples
cssshapescss-shapes

CSS space invader with only one element


There is a lot of shapes that we can make with pure CSS, like in http://nicolasgallagher.com/pure-css-gui-icons/demo/ and you always write one element (here <li>).

But if we want shapes that are a little bit more complexe, like http://www.gentegeek.com/proyectos/html-css-space-invaders/ we must put a lot of <div> (see the source code).

Can I make shapes with only one element? If yes, how?


Solution

  • Yes! -- With CSS3

    However, it is probably not worth the effort in most cases. Essentially, given enough forethought and patience, you can "paint" practically any pixel based shape (like your example) using linear-gradient.

    Here is a fiddle. (Updated to allow for transparency of image areas itself).

    The code is a single div element (per your request). The css is as follows (I've not posted all the vendor prefix equivalents here).

    div {
        width: 240px;
        height: 160px;
        background-repeat: no-repeat;
        background-position: 0 0, 0 20px, 0 40px, 0 70px, 0 90px, 0 100px, 0 120px, 0 140px;
        background-size: 240px 20px, 240px 20px, 240px 30px, 240px 20px, 240px 10px, 240px 20px, 240px 20px, 240px 20px;
        background-image:
            linear-gradient(left, transparent 0px, transparent 40px, #000 41px, #000 60px, transparent 61px, transparent 180px, #000 181px, #000 200px, transparent 201px, transparent 240px ),
            linear-gradient(left, #000 0px, #000 20px, transparent 21px, transparent 60px, #000 61px, #000 80px, transparent 81px, transparent 160px, #000 161px, #000 180px, transparent 181px, transparent 220px, #000 221px, #000 240px),
            linear-gradient(left, #000 0px, #000 20px, transparent 21px, transparent 40px, #000 41px, #000 200px, transparent 201px, transparent 220px, #000 221px, #000 240px),
            linear-gradient(left, #000 0px, #000 60px, transparent 61px, transparent 80px, #000 81px, #000 160px, transparent 161px, transparent 180px, #000 181px, #000 240px),
            linear-gradient(left, #000, #000),
            linear-gradient(left, transparent 0px, transparent 20px, #000 21px, #000 220px, transparent 221px, transparent 240px ),
            linear-gradient(left, transparent 0px, transparent 40px, #000 41px, #000 60px, transparent 61px, transparent 180px, #000 181px, #000 200px, transparent 201px, transparent 240px ),
            linear-gradient(left, transparent 0px, transparent 20px, #000 21px, #000 40px, transparent 41px, transparent 200px, #000 201px, #000 220px, transparent 221px, transparent 240px );
    }