使用R的bookdown::gitbook实现图片居中但图注左对齐的方法
要实现bookdown::gitbook输出中图片居中、图注左对齐的效果,最简洁的方案是通过自定义CSS控制元素样式,操作步骤如下:
步骤1:添加自定义CSS文件
在你的项目根目录新建名为custom.css的文件,写入以下内容:
/* 控制figure容器整体适配页面宽度 */ figure { width: 100%; text-align: center; } /* 单独设置图片居中显示 */ figure img { display: block; margin: 0 auto; } /* 单独设置图注左对齐,可根据需要调整max-width适配页面宽度 */ figure figcaption { text-align: left !important; max-width: 90%; margin: 1em auto 0 auto; }
步骤2:修改YAML配置引入CSS
更新你的文档头部YAML输出配置,将自定义CSS加入bookdown::gitbook的参数中,修改后的配置如下:
--- title: "Notes for An Introduction to Statistical Learning with Applications in R, Second Edition" author: "me" date: "`r Sys.Date()`" site: bookdown::bookdown_site documentclass: book output: bookdown::gitbook: config: toc: collapse: false fig_caption: true number_sections: true global_numbering: true css: "custom.css" # 新增这一行引入自定义样式 description: "Notes for ISLR2" ---
步骤3:调整代码块参数
配置完成后,你可以删掉原来代码块里的fig.align="center"参数,样式会由全局CSS统一控制,所有图片都会自动居中、图注左对齐,不需要逐块设置。如果需要个别块的样式和全局不同,也可以单独给代码块加out.extra参数自定义样式,优先级高于全局CSS。
内容的提问来源于stack exchange,提问作者itsMeInMiami
相关产品推荐
相关产品推荐

