How to create a Sierpinski triangle in LaTeX?

The width of the background triangles is 2^order*stepsize, so you can calculate the step size as a function of the desired overall width:

\documentclass[border=5mm]{standalone}
\usepackage{tikz}

\usetikzlibrary{lindenmayersystems}

\begin{document}%
\def\trianglewidth{2cm}%
\pgfdeclarelindenmayersystem{Sierpinski triangle}{
    \symbol{X}{\pgflsystemdrawforward}
    \symbol{Y}{\pgflsystemdrawforward}
    \rule{X -> X-Y+X+Y-X}
    \rule{Y -> YY}
}%
\foreach \level in {0,...,3}{%
\tikzset{
    l-system={step=\trianglewidth/(2^\level), order=\level, angle=-120}
}%
\begin{tikzpicture}
    \fill [black] (0,0) -- ++(0:\trianglewidth) -- ++(120:\trianglewidth) -- cycle;
    \draw [draw=none] (0,0) l-system
    [l-system={Sierpinski triangle, axiom=X},fill=white];
\end{tikzpicture}
}%
\end{document}

An alternative way using decorations. It's a bit dependent on how the initial triangle is drawn (i.e., the direction of the path), and the nesting of decorations has to be done manually.

\documentclass[border=5pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{decorations}

% Not sure this follows any proper defition of 
% Sirpinksi triangle. It just works.
\pgfdeclaredecoration{quasi-sirpinski}{do}{%
    \state{do}[width=\pgfdecoratedinputsegmentlength, next state=do]{%
        \pgfpathmoveto{\pgfpointpolar{-60}{\pgfdecoratedinputsegmentlength/2}}%
        \pgfpathlineto{\pgfpointorigin}%
        \pgfpathlineto{\pgfpoint{\pgfdecoratedinputsegmentlength/2}{0pt}}%
        \pgfpathclose%
    }
}

\begin{document}

\tikz
    \fill (0,0) -- ++(60:3) -- ++(-60:3) -- cycle;

\tikz[decoration=quasi-sirpinski]
    \fill decorate { (0,0) -- ++(60:3) -- ++(-60:3) -- cycle };

\tikz[decoration=quasi-sirpinski]
    \fill decorate { decorate { 
        (0,0) -- ++(60:3) -- ++(-60:3) -- cycle } };

\tikz[decoration=quasi-sirpinski]
    \fill decorate { decorate { decorate { 
        (0,0) -- ++(60:3) -- ++(-60:3) -- cycle } } };

\tikz[decoration=quasi-sirpinski]
    \fill decorate { decorate { decorate {  decorate {
        (0,0) -- ++(60:3) -- ++(-60:3) -- cycle } } } };

\end{document}

enter image description here


\documentclass[pstricks]{standalone}
\usepackage{pst-fractal}
\begin{document}

\multido{\iA=1+1}{5}{%
 \begin{pspicture}(3,2.8)
 \psSier[linecolor=blue!70,fillcolor=red!40](0,0){3cm}{\iA}
 \end{pspicture}}

 \multido{\iA=1+1}{5}{%
   \begin{pspicture}(3,2.7)\psSier(0,0){3cm}{\iA}
\end{pspicture}}


\end{document}

enter image description here

enter image description here