Alex D. Alex D. - 2 months ago 8
CSS Question

How to draw heart using HTML/CSS table?

I'm trying to draw heart:

enter image description here

using HTML table's nth-child property, but can't figure out how to do it: Codepen

table tr td:nth-child(n+3):nth-child(-n+7) {
background-color: red;
}

Answer

If you really only want to use the 'nth-child' then use the following:

First row:

table tr:nth-child(1) td:nth-child(3),
table tr:nth-child(1) td:nth-child(5) {
  background-color:red;
}

So, in your table, the first tr followed by the 3rd and 5th td should have red background. Apply the same logic for all the following rows.

For the second row you could use the nth-last-child too:

table tr:nth-child(2) td:nth-child(n+2):nth-last-child(n+4) {
  background-color:red;
}

The whole solution then comes out like this:

table tr:nth-child(2) td:nth-child(4),
table tr:nth-child(2) td:nth-child(6),
table tr:nth-child(3) td:nth-child(n+3):nth-last-child(n+3),
table tr:nth-child(4) td:nth-child(n+3):nth-last-child(n+3),
table tr:nth-child(5) td:nth-child(n+4):nth-last-child(n+4),
table tr:nth-child(6) td:nth-child(n+5):nth-last-child(n+5) {
  background-color:red;
}

If you were looking for a formula that describes a heart shape, then you could start here for example: http://mathworld.wolfram.com/HeartCurve.html

But implementing such a formula is out of scope of CSS I think.