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!

  • you could replace the % by \nopagebreak – David Carlisle Jul 23 '18 at 10:07
  • 1
    I can confirm egreg's comment: \nopagebreak does not work. – Pygmalion Jul 23 '18 at 10:19
  • 1
    hmph it could be made to work:-) @egreg can answer – David Carlisle Jul 23 '18 at 10:21
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}
\]
  • 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

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.