5

Is it possible to construct a small, color-filled box in text among ordinary text? The size of the box should correspond to the font size.

I need it because I need to construct a legend for some graphics that I have constructed elsewhere.

4

With \fontcharht it's easy:

\documentclass{article}
\usepackage{xcolor}

\newcommand{\legendbox}[1]{%
  \textcolor{#1}{\rule{\fontcharht\font`X}{\fontcharht\font`X}}%
}

\begin{document}
\legendbox{blue} This is some text \legendbox{red}

\Large\legendbox{blue} This is some text \legendbox{olive}

\Huge\legendbox{blue!60} This is some text \legendbox{green!20}
\end{document}

enter image description here

6
\documentclass{article}
\usepackage{xcolor}
\usepackage{scalerel}
\newcommand*{\mybox}[1][red]{\scalerel*{\textcolor{#1}{\rule{1ex}{1ex}}}{d}}
\begin{document}
  \mybox[blue] This is some text \mybox{} Again \mybox[olive]

  \Large\mybox[blue] This is some text \mybox{} Again \mybox[olive]

  \Huge\mybox[blue] This is some text \mybox{} Again \mybox[olive]
\end{document}

enter image description here

Without scalerel also this works since ex units are used:

\documentclass{article}
\usepackage{xcolor}
\newcommand*{\mybox}[1][red]{\textcolor{#1}{\rule{1.5ex}{1.5ex}}}
\begin{document}
  \mybox[blue] This is some text \mybox{} Again \mybox[olive]

  \Large\mybox[blue] This is some text \mybox{} Again \mybox[olive]

  \Huge\mybox[blue] This is some text \mybox{} Again \mybox[olive]
\end{document}

enter image description here

Here you have to set 1.5ex as you wish once.

  • Perhaps a multi-scale demo would be useful, as in \mybox[blue] This is some text \mybox{} Again \mybox[olive]\Large\mybox[blue] This is some text \mybox{} Again \mybox[olive] – Steven B. Segletes Jan 22 '15 at 13:40
  • @StevenB.Segletes Thanks and added :-) – user11232 Jan 22 '15 at 13:44
  • Thank you. Is there a different way that does not apply scalerel? For some reason, my compiler is not able to find scalerel.sty despite it being in the "\texmf-dist\tex\latex" folder. – Marcus Jan 22 '15 at 14:22
  • @Marcus Please see the update. – user11232 Jan 22 '15 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.