3

I have very often a situation when I want that the center environment is glued to the preceding text, something like that:

Some text
%
\begin{center}
\begin{tikzpicture}
some commands
\end{tikzpicture}
\end{center}

Is it possible to make a general solution for that, for example defining new environment based on center or completely new environment to do the task?

Thanks for answers!

Pygmalion
  • 6,387
  • 4
  • 34
  • 68

1 Answers1

2

The \center environment uses \trivlist and issues an \item command, that adds \@beginparpenalty, which is usually −51. Thus a page break point is always available before center.

\documentclass{article}
\usepackage[lines=7]{geometry}
\usepackage{lipsum}

\makeatletter
\newenvironment{gluecenter}
 {\@beginparpenalty\@M\center}
 {\endcenter}
\makeatletter

\begin{document}

\lipsum*[2]
\begin{gluecenter}
This should stay
\end{gluecenter}

\end{document}

enter image description here

With center the centered line would be on a page by itself (the \lipsum paragraph has seven lines).

Another solution is to (ab)use displaymath, because a tikzpicture is independent on the mode it is called in.

Some text
\[
\begin{tikzpicture}
...
\end{tikzpicture}
\]
egreg
  • 1,121,712
  • Thanks a lot. I decided for gluecenter, because I don't like to abuse things :) – Pygmalion Jul 23 '18 at 10:33
  • @Pygmalion For a tikzpicture I'd go with \[...\]. – egreg Jul 23 '18 at 10:34
  • Could you, in couple of words, say why? – Pygmalion Jul 23 '18 at 10:39
  • 1
    @Pygmalion The display math mechanism is designed not to add a page break point before it and exploiting this method for adding a graphic object that must stay there is not a real abuse. – egreg Jul 23 '18 at 10:40
  • 1
    It should be noted that gluecenter always leaves two text lines together with the picture, which is a plus compared to \[/\] – Pygmalion Jul 23 '18 at 10:53
  • Your answer was extremely helpful. But now I realised that few center environments should be glued below or above and below. Is this also possible to do? Shall I open another question or revise the current one? – Pygmalion Jul 23 '18 at 11:06
  • @Pygmalion For below, it's a completely different matter. – egreg Jul 23 '18 at 11:16