html - 将父 div 居中,而 width 检索子 div 的宽度值

标签 html css

如标题所述,我想将父 div 居中,其中父 div 检索其所有子 div 的宽度。

这是我用来检索子 div 宽度的代码:

.parent
{
    background-color: yellow;
    display: inline-block;
    font-size: 0;
    /*How could I center this div? I used to do: margin-left: auto; margin-right: auto;
    however for this I need to assign a fixed width. I want to assign the width of the
    content inside the div.*/
}

.child
{
    height: 100px;
    width: 100px;
    border: 1px solid red;
    display: inline-block;
}

来源:http://jsfiddle.net/53me4f8e/

如何让这个 div 居中?

最佳答案

居中对齐父元素的文本,在本例中为 body.parent 显示为 inline-block,这意味着它的行为类似于内联元素,因此居中:

body{
    text-align: center;
}

请注意,因为 text-align 是继承的,您可能希望将文本对齐恢复为 left(或 right,具体取决于.parent 的偏好):

.parent{
  text-align: left;
  /* Other styles.. */
}

JSFiddle

关于html - 将父 div 居中,而 width 检索子 div 的宽度值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30667639/

相关文章:

jquery - 悬停时滑动停止 - responsive-slider.js ( w3widgets)

jquery - 在页面上查找某些文本并为其添加下划线

javascript - 滑动 slider - 用于加载图像的模糊技术

html - 调整窗口大小时从左下角制作背景图像 "grow"

html - 内容不拉伸(stretch)

jquery - 将跨度位置设置为中心

javascript - jquery或javascript是否有类似(flash中的onEnterFrame)的功能

android - ReactJS 中的隐形 View

php - CSS Div 标签不起作用

html - 导航和标题不会居中