[Tex/LaTex] (Framed) Boxes are too long / Textwidth doesn’t work

boxeswidth

I want to create a box/frame (in math mode) with its content centered horizontally and vertically such that I can adjust the height of the box and such the width of the box automatically (!) is the width of the context.

The following MWE does almost what I want:

\documentclass[12pt,a4paper]{article}
\usepackage[latin1]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\begin{document}

$\fbox{\parbox[c][4pt][c]{\textwidth}{a first try}}$

$\framebox[\width]{\parbox[c][2pt][c]{\textwidth}{another one}}$

\end{document}

The problems are the following:

  • both of the boxes aren't as long as their contents, i.e. as long as "a first try" resp. "another one", so \textwidthdoesn't seem to work very well. Of course I could manually try to adjust the width to the right size, but I'm going to create boxes very often so fiddling with the width every time to get it right is unfeasible.

  • the vertical centering doesn't work very well since in both boxes the text is moved to the top

I'm open to different approaches to this, as long as they do what I want, like defining new commands – for example with tikz – that do what I want, as long as I don't have to type very much for using them, since as I said, I will need to create a lot of boxes.
Btw., using to box commands to almost achieving this is a lot of typing – I would be happy if only one command would suffice.

EDIT

The height of the box usually is like this: enter image description here whereas I would like it to be like this: enter image description here, i.e. the box should just barely cover it's contents vertically. Decrease the height parameter in \fbox does nothing after a certain point (the first box was created with height of 8pt and decreasing it didn't do anything; to get the second picture I edited the first in some editing program)

Best Answer

Your lines are overfull in both directions.

Horizontally the line contains

  • 1 paragraph indentation
  • 1 rule of thickness \fboxrule
  • padding space of \fboxsep
  • 1 box of width \textwidth
  • padding space of \fboxsep
  • 1 rule of thickness \fboxrule

This comes to more than \textwidth :-) I adjust for that below. I left in the $ although they are doing nothing, the contents of a box always start in text mode.

Vertically you have a row of 10pt text being forced into a box with vertical size 4pt.

To use the natural width however you don't want \parbox at all, just use \fbox:

enter image description here

\documentclass[12pt,a4paper]{article}
\usepackage[latin1]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\begin{document}

\noindent$\fbox{\parbox[c][15pt][c]{\dimexpr\textwidth-2\fboxsep-2\fboxrule}%
       {a first try}}$


\noindent$\fbox{\rule[-20pt]{0pt}{40pt}a first try}$



\end{document}