0、背景
我Windows平臺上用的Markdown編輯器是MarkdownPad,這個工具大部分有一個讓我不爽的地方:默認地,導(dǎo)出的html或者pdf中圖片都是左對齊,而不是居中。因為它支持自定義css,所以,這里想通過設(shè)置css來實現(xiàn)圖片的居中。
1、需求
首先要明白編輯器中,Markdown中對圖片的處理,加入通過下面的markdown語法插入一張圖片:

那么,最終得到的HTML中對應(yīng)的代碼是:

可以看出,這里的img標簽是包裹在p標簽里面的。這里的需求就是,要包裹p標簽中的img標簽設(shè)置居中樣式。
2、實現(xiàn)
2.1 一般的設(shè)置圖片居中的方法
首先明確img標簽是行內(nèi)元素(inline),不是塊元素(block)。所以,要想設(shè)置圖片居中,大部分是通過圖片元素的父元素設(shè)置style="text-align:center;"來實現(xiàn)的:

如果通過這條路,來設(shè)置居中,就需要CSS中有一個選擇器能夠選中包含img元素的p元素。然而,到目前,CSS還沒有這樣一個選擇器。原因如下:
CSS does not include parent selectors (a method of styling a parent based on what children it contains). This fact has been stackflow posters, but it turns out there is a very good reason for its absence. Particularly in the early days of the Internet, it was considered critically important that the page be renderable before the document has been fully loaded. In other words, we want to be able to render the beginning of the HTML to the page before the HTML which will form the bottom of the page has been fully downloaded.
A parent selector would mean that styles would have to be updated as the HTML document loads. Languages like DSSSL were completely out, as they could perform operations on the document itself, which would not be entirely available when the rendering is to begin.
2.2 這里采用的方法
先上代碼:

用上面的代碼,可以發(fā)現(xiàn),通過將img元素的展示方式設(shè)置為block(獨占一行),然后左右外邊距設(shè)置為auto(邊距由瀏覽器自動計算,看來兩邊都自動計算的結(jié)果就是居中_),可以實現(xiàn)圖片的居中顯示。
這樣,在markdown編輯器的自定義CSS中,添加如下規(guī)則:
img {
margin-left: auto;
margin-right:auto;
display:block;
}
即可實現(xiàn)圖片的自動水平居中,而且在預(yù)覽窗口中也生效。
下面的代碼,是一個在markdown中的插入圖片的例子,可以用于測試Markdown中的圖片有沒有居中。


3、寫在后面
本人小白,對于這個問題,如果有什么更好的實現(xiàn)方法,歡迎留言交流~