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

标签 css

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

我使用了以下代码:

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

但它使 DIV 元素本身居中。

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

text-align 的问题是,它只能水平对齐。

最佳答案

这应该为你做:

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 */
}

关于CSS - 居中 DIV 内容,而不是 DIV 本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1695669/

相关文章:

html - 如何选择h4标题

css - 将Wrap Bootstrap主题与Ruby on Rails集成

javascript - 仅使用 DIV 在 JavaScript 中制作时钟

javascript - 如何创建自动生成的备用表格行颜色?

html - 改变 div 的宽度是向左移动元素

jQuery BootStrap 加载顺序

jquery - 当前字段为空时使用 Shift+Tab 返回上一字段

javascript - 定位从固定到静态

css - rails 4 : properly using content_for/rendering partials

css - 边框中的背景渐变?