代码之家  ›  专栏  ›  技术社区  ›  user366312

CSS-将DIV内容居中,而不是DIV本身

css
  •  0
  • user366312  · 技术社区  · 15 年前

    如何使DIV元素中的内容居中(我的DIV元素可能包含图像元素或其他元素)?

    我使用了以下代码:

    div#containerDiv
    {
        margin-left: auto ;
        margin-right: auto ;
    }
    

    但它是DIV元素本身的中心。

    我希望内容(即DIV中的图像元素)居中。

    文本对齐的问题是,它只能水平工作。

    2 回复  |  直到 15 年前
        1
  •  3
  •   Sam Becker    15 年前

    这应该为您做到:

    div#containerDiv
    {
        margin-left: auto ;
        margin-right: auto ;
        text-align: center ;
    }
    

    为了回应你的评论,很难按照你想要的方式垂直对齐某个东西。我建议你做如下的事情:

    div#containerDiv > img
    {
         margin-top: 15px ; 
         /* Where 15 is the amount of space required to center the image */
    }
    
        2
  •  0
  •   xentek    15 年前

    如果将显示设置为“表格单元格”,则有时可以不使用垂直对齐属性。不是在每一个浏览器中都能正常工作,而是可以玩的东西。