美文网首页css学习css实用前端
CSS设置图片水平居中

CSS设置图片水平居中

作者: SpaceCat | 来源:发表于2016-12-08 23:38 被阅读5168次

    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:https://img.haomeiwen.com/i744204/3ab4f07b5f0e7a7d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    
    Test Image

    3、写在后面

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

    相关文章

      网友评论

      • 安卓猿:很好,安卓猿路过, 表示 webview 此法有效,
        SpaceCat:@安卓猿 哈哈
        SpaceCat:@安卓猿 哈哈
      • 好好顽:哈哈你的思路就是正确的
        这样写更简洁
        ```
        img {
        margin:0 auto;
        display:block;
        }
        ```
        SpaceCat: @好好顽 嗯,对。谢啦😀

      本文标题:CSS设置图片水平居中

      本文链接:https://www.haomeiwen.com/subject/iaosmttx.html