如何创建仅占用子元素宽度(不指定固定像素宽度)的DIV?

时间:2021-06-04 20:05:53

I would like to have a DIV around my elements that only occupies as much horizontal width as the maximum horizontal width of its elements. I have these HTML elements …

我希望在我的元素周围有一个DIV,它只占用与其元素的最大水平宽度一样多的水平宽度。我有这些HTML元素......

<div id="container-content">
    <h3>My Subscriptions</h3> 
    <table id="subscriptions-table">
        . . .
    </table>
</div>

and this style

而这种风格

#container-content {
    text-align: center;
    background-color: red;
}

#subscriptions-table {
    margin: 0 auto;
}

but disappointingly, the DIV with class = “container-content” occupies 100% of the width of the screen ( https://jsfiddle.net/ya8b11qf/ ) and I would prefer it only take up as much width as the table within it. I do not want to specify a fixed pixel width for “container-content”.

但令人失望的是,带有class =“container-content”的DIV占据了屏幕宽度的100%(https://jsfiddle.net/ya8b11qf/),我希望它只占用其中的表格宽度。我不想为“container-content”指定固定的像素宽度。

1 个解决方案

#1


2  

This can be accomplished by applying display: inline-block; to the container, like so:

这可以通过应用display:inline-block;到容器,像这样:

#container-content {
    text-align: center;
    background-color: red;
    display: inline-block;
}

And your updated JSFiddle: https://jsfiddle.net/ya8b11qf/1/

和你更新的JSFiddle:https://jsfiddle.net/ya8b11qf/1/

To center #container-content, just add text-align: center; to its parent. Because the content is now displaying inline, it responds to text-centering, whereas a standard div (which is block display by default) requires the use of margin: 0 auto;.

要将#container-content设为中心,只需添加text-align:center;给它的父母。因为内容现在显示内联,它响应文本居中,而标准div(默认情况下是块显示)需要使用margin:0 auto;。

#1


2  

This can be accomplished by applying display: inline-block; to the container, like so:

这可以通过应用display:inline-block;到容器,像这样:

#container-content {
    text-align: center;
    background-color: red;
    display: inline-block;
}

And your updated JSFiddle: https://jsfiddle.net/ya8b11qf/1/

和你更新的JSFiddle:https://jsfiddle.net/ya8b11qf/1/

To center #container-content, just add text-align: center; to its parent. Because the content is now displaying inline, it responds to text-centering, whereas a standard div (which is block display by default) requires the use of margin: 0 auto;.

要将#container-content设为中心,只需添加text-align:center;给它的父母。因为内容现在显示内联,它响应文本居中,而标准div(默认情况下是块显示)需要使用margin:0 auto;。