CSS設(shè)置圖片水平居中

0、背景

我Windows平臺上用的Markdown編輯器是MarkdownPad,這個工具大部分有一個讓我不爽的地方:默認地,導(dǎo)出的html或者pdf中圖片都是左對齊,而不是居中。因為它支持自定義css,所以,這里想通過設(shè)置css來實現(xiàn)圖片的居中。

1、需求

首先要明白編輯器中,Markdown中對圖片的處理,加入通過下面的markdown語法插入一張圖片:

![Test Image](http://www.jianshu.io/test.jpg)

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


markdown img to html

可以看出,這里的img標簽是包裹在p標簽里面的。這里的需求就是,要包裹p標簽中的img標簽設(shè)置居中樣式。

2、實現(xiàn)

2.1 一般的設(shè)置圖片居中的方法

首先明確img標簽是行內(nèi)元素(inline),不是塊元素(block)。所以,要想設(shè)置圖片居中,大部分是通過圖片元素的父元素設(shè)置style="text-align:center;"來實現(xiàn)的:

general omg align center method

如果通過這條路,來設(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.

From: https://www.zhihu.com/question/20443379

2.2 這里采用的方法

先上代碼:

set margin auto to make omg align center

用上面的代碼,可以發(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中的圖片有沒有居中。

![Test Image](http://upload-images.jianshu.io/upload_images/744204-3ab4f07b5f0e7a7d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
Test Image

3、寫在后面

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 問答題47 /72 常見瀏覽器兼容性問題與解決方案? 參考答案 (1)瀏覽器兼容問題一:不同瀏覽器的標簽?zāi)J的外補...
    _Yfling閱讀 14,093評論 1 92
  • 本課來自http://www.imooc.com/learn/9請不要用作商業(yè)用途。 HTML5 HTML介紹 H...
    PYLON閱讀 3,439評論 0 5
  • 本文主要是起筆記的作用,內(nèi)容來自慕課網(wǎng). 認識CSS樣式 CSS全稱為“層疊樣式表 (Cascading Styl...
    0o凍僵的企鵝o0閱讀 2,748評論 0 30
  • 一 外部式css樣式 (也可稱為外聯(lián)式)就是把css代碼寫一個單獨的外部文件中,這個css樣式文件以“.css...
    KunMitnic閱讀 1,110評論 0 1
  • “hey,來根煙” “走,去廁所” “嗯,給你!” “有火嗎?” 3月1號,深圳也開始全面禁煙了,已經(jīng)過去一個多月...
    山楂葉閱讀 511評論 0 1

友情鏈接更多精彩內(nèi)容