避免自定义环境后间距加倍的系统

避免自定义环境后间距加倍的系统

下面是一个非常简单的例子,用于说明环境前后的间距问题:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{xcolor}

% Define the theorem environment
\newenvironment{question}[1][]
  {\vspace{1cm}
  \begin{theorem}
    \color{blue}
    \if\relax\detokenize{#1}\relax
    \else
      \textbf{#1.}\hspace{3pt}
    \fi}
  {\end{theorem}\vspace{1cm}}

% Define the theorem style
\theoremstyle{definition}
\newtheorem{theorem}{Question}

\begin{document}

\section{Custom Theorem Environment}

\begin{question}[My Custom Question 1]
  What is the meaning of life, the universe, and everything?
  \end{question}

This is working really nicely

\begin{question}[My Custom Question 2]
  How can we ensure world peace?
  \end{question}

%\vspace{-1cm} % - manual fix to the problem

\begin{question}[My Custom Question 3]
  But if we have two questions one after each other we get a double up of spacing
  \end{question}

\end{document}

这里,我们有一个自定义环境,前后各有 1cm 的填充。当调用环境时,中间有文本时,这种方法很有效。但是,当一个接一个地调用环境时,文本就会加倍。有没有办法通过自动解决方案来避免这种情况?我已经手动注释了什么会抑制这种影响,但我正在寻找一种可以自动处理此问题的解决方案。

遇到的问题:

在此处输入图片描述

理想输出:

在此处输入图片描述

答案1

考虑使用\addvspace{1cm}而不是\vspace{1cm}。前者仅添加不超过指定最大长度的空间。

在此处输入图片描述

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{xcolor}

% Define the theorem environment
\newenvironment{question}[1][]{%
  \par% Ensure you're in vertical mode
  \addvspace{1cm}
  \begin{theorem}
    \color{blue}%
    \if\relax\detokenize{#1}\relax
    \else
      \textbf{#1.}\hspace{3pt}
    \fi}
  {\end{theorem}\addvspace{1cm}}

% Define the theorem style
\theoremstyle{definition}
\newtheorem{theorem}{Question}

\begin{document}

\section{Custom Theorem Environment}

\begin{question}[My Custom Question 1]
What is the meaning of life, the universe, and everything?
\end{question}

This is working really nicely

\begin{question}[My Custom Question 2]
How can we ensure world peace?
\end{question}

\begin{question}[My Custom Question 3]
But if we have two questions one after each other we get a double up of spacing
\end{question}

\end{document}

相关内容