CSS设置图片水平居中

0、背景

我Windows平台上用的Markdown编辑器是MarkdownPad,这个工具大部分有一个让我不爽的地方:默认地,导出的html或者pdf中图片都是左对齐,而不是居中。因为它支持自定义css,所以,这里想通过设置css来实现图片的居中。

1、需求

首先要明白编辑器中,Markdown中对图片的处理,加入通过下面的markdown语法插入一张图片:

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

那么,最终得到的HTML中对应的代码是:


markdown img to html

可以看出,这里的img标签是包裹在p标签里面的。这里的需求就是,要包裹p标签中的img标签设置居中样式。

2、实现

2.1 一般的设置图片居中的方法

首先明确img标签是行内元素(inline),不是块元素(block)。所以,要想设置图片居中,大部分是通过图片元素的父元素设置style="text-align:center;"来实现的:

general omg align center method

如果通过这条路,来设置居中,就需要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

用上面的代码,可以发现,通过将img元素的展示方式设置为block(独占一行),然后左右外边距设置为auto(边距由浏览器自动计算,看来两边都自动计算的结果就是居中_),可以实现图片的居中显示。

这样,在markdown编辑器的自定义CSS中,添加如下规则:

img {
    margin-left: auto; 
    margin-right:auto; 
    display:block;
}

即可实现图片的自动水平居中,而且在预览窗口中也生效。

下面的代码,是一个在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、写在后面

本人小白,对于这个问题,如果有什么更好的实现方法,欢迎留言交流~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,806评论 1 92
  • 本课来自http://www.imooc.com/learn/9请不要用作商业用途。 HTML5 HTML介绍 H...
    PYLON阅读 3,318评论 0 5
  • 本文主要是起笔记的作用,内容来自慕课网. 认识CSS样式 CSS全称为“层叠样式表 (Cascading Styl...
    0o冻僵的企鹅o0阅读 2,664评论 0 30
  • 一 外部式css样式 (也可称为外联式)就是把css代码写一个单独的外部文件中,这个css样式文件以“.css...
    KunMitnic阅读 962评论 0 1
  • “hey,来根烟” “走,去厕所” “嗯,给你!” “有火吗?” 3月1号,深圳也开始全面禁烟了,已经过去一个多月...
    山楂叶阅读 472评论 0 1