css设置图标居左_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.

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、写在后面

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值