我有一张表格,但有些行比其他行大,因为有些行的高度因 而改变p{2cm}
。在这种情况下,最好将行居中。建议的解决方案是使用\arraystretch
,但这不可行,因为它甚至会拉伸这些不需要任何更改的行,使本来就很大的表格不必要地变得更大。
\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{float}
\usepackage{makecell}
\usepackage{multirow}
\begin{document}
\section{Introduction}
\begin{table}[!htbp]
\small
\begin{center}
\begin{tabular}{ |>{\centering\arraybackslash}p{2cm}||c|c|c|c|c| }
\hline
\multirow{2}{*}{} & \multicolumn{5}{c|}{Some text} \\
\cline{2-6}
& 1 & 2 & 3 & 4 & 5 \\
\hline
\hline
Row 1 & val1 & val2 & val2 & val3 & val4 \\
\hline
Row 2 but this one is very long & val1 centered & val2 centered & val2 centered & val3 centered & val4 centered \\
\hline
\end{tabular}
\end{center}
\caption{table} \label{lbl}
\end{table}
\end{document}
答案1
考虑@DavidCarlisle 的评论:
\documentclass[12pt]{article}
%---------------- show page layout. don't use in a real document!
\usepackage{showframe}
\renewcommand\ShowFrameLinethickness{0.15pt}
\renewcommand*\ShowFrameColor{\color{red}}
%---------------------------------------------------------------%
%\usepackage[utf8]{inputenc} % it is part of LaTeX, you not need to load anymore
%\usepackage{float} % not used
%\usepackage{makecell} % not used
\usepackage{array} % needed for define `m` column type
\usepackage{multirow}
\begin{document}
\section{Introduction}
\begin{table}[!htbp]
\small
%\begin{center} % table is nicer, if you replace it with `\centering`
\begin{tabular}{ |>{\centering\arraybackslash}m{2cm}||c|c|c|c|c| }
\hline
\multirow{2}{*}{} & \multicolumn{5}{c|}{Some text} \\
\cline{2-6}
& 1 & 2 & 3 & 4 & 5 \\
\hline
\hline
Row 1 & val1 & val2 & val2 & val3 & val4 \\
\hline
Row 2 but this one is very long & val1 centered & val2 centered & val2 centered & val3 centered & val4 centered \\
\hline
\end{tabular}
\end{center}
\caption{table} \label{lbl}
\end{table}
\end{document}
(红线表示页面布局)
如您所见,您的表格比页面上的可用文本空间要宽。要纠正此问题,您有两个选择:
\textwidth
通过使用geometry
包增加- 启用自动拆分表格中所有单元格的单元格内容。为此,您应该定义
m
列类型或使用tabularx
表格,重新定义X
列以
\renewcommand\tabularxcolumn[1]{m{#1}}
或使用tabularray
包。
使用包的第二个选项的示例tabularray
:
\documentclass[12pt]{article}
\usepackage{tabularray}
\begin{document}
\section{Introduction}
\begin{table}[!htbp]
\small
\begin{tblr}{hlines, vlines,
colspec = {Q[c, m, wd=20mm] *{5}{X[c, m]}}
}
\SetCell[r=2]{c}
& \SetCell[c=5]{c} Some text
& & & & \\
& 1 & 2 & 3 & 4 & 5 \\
Row 1 & val1 & val2 & val2 & val3 & val4 \\
Row 2 but this one is very long
& val 1 centered & val 2 centered & val 2 centered & val 3 centered & val 4 centered \\
\end{tblr}
\caption{table} \label{lbl}
\end{table}
\end{document}