Markdown 让你专注于内容而不是格式,但是有时候你确实想要控制一下显示效果,比如说图片。在 markdown 中,图片是通过这样的方式插入的:

1
![test image size](/img/post-bg-2015.jpg)

默认是最大化,如果我们想要控制图片的显示大小,怎么做呢?最简单直观的做法就是使用原始的 HTML 标签:

1
<img src="http://arganzheng.life/img/post-bg-2015.jpg" height="100px" width="400px" >

但是这样子就不是纯粹的 markdown 文本了,是 markdown 跟 html 的混合体,当然图片这个 html 标签还算是简洁。

另一种方式就是通过外部的 CSS 控制,对 post 中的所有 img 做统一处理:

1
2
3
4
5
img[alt=img_alt_you_want_to_control] {
width: 70%;
border: none;
background: none;
}

然后对于你想要控制显示效果的 img 使用这个 alt:

1
![img_alt_you_want_to_control](/img/post-bg-2015.jpg)

不过这种方式对所有的 img 显示效果统一处理了,而且对 alt 有要求(当然你可以用其他的方式定位到文章中的 img),不是很灵活。

谷歌了一下,发现其实有些 markdown 实现是支持指定图片属性的,如 kramdown :

Here is an inline ![smiley](smiley.png){:height="36px"width="36px"} .

会渲染成:

1
<img src="http://arganzheng.life/smiley.jpg" alt="smiley" height="36px" width="36px">

所以我们可以这么指定:

1
2
3
![test image size](/img/post-bg-2015.jpg){:class="img-responsive"}
![test image size](/img/post-bg-2015.jpg){:height="50%" width="50%"}
![test image size](/img/post-bg-2015.jpg){:height="100px" width="400px"}

渲染结果如下:

1
2
3
<img src="http://arganzheng.life/img/post-bg-2015.jpg" alt="test image size" class="img-responsive">
<img src="http://arganzheng.life/img/post-bg-2015.jpg" alt="test image size" height="50%" width="50%">
<img src="http://arganzheng.life/img/post-bg-2015.jpg" alt="test image size" height="100px" width="400px">

因为我们没有在 CSS 上定义 img-responsive class,所以这里第一个没有效果。

你需要在你的 jekyll 配置文件 (_config) 中告诉它使用 kramdown 渲染:

1
2
3
4
5
6
7
# Markdown settings
# replace redcarpet to kramdown,
# although redcarpet can auto highlight code, the lack of header-id make the catalog impossible, so I switch to kramdown
# document: http://jekyllrb.com/docs/configuration/#kramdown
markdown: kramdown
kramdown:
input: GFM # use Github Flavored Markdown !important

TIPS

1、上面第二种方式,也可以使用隐藏的 html 标签做控制:

1
2
![test image size](/img/post-bg-2015.jpg)<!-- .element height="50%" width="50%" -->
![test image size](/img/post-bg-2015.jpg)<!-- .element style="border: 0; background: None; box-shadow: None" -->

不过个人感觉还是 kramdown 的语法简单明了。

2、细心的读者可能会发现图片的显示效果不是 400x100,这是因为我在 CSS 中对 post 中的所有 img 做了统一的处理:

1
2
3
4
5
6
.post-container img {
display: block;
max-width: 100%;
height: auto;
margin: 1.5em auto 1.6em;
}

所以上面 height 的指定其实是没有效果的,我只需要控制好 width 就可以了,这样可以避免变形。

Enjoy writing!

–EOF–

参考文章

  1. Inserting Images in Markdown Jekyll Posts

最后更新: 2019年11月07日 04:19

原始链接: https://airbash.cn/2019/11/07/Markdown/ImgSize/

× 请我吃糖~
打赏二维码