CSS Div Size 自动调整内容大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3751511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 22:48:03  来源:igfitidea点击:

Div Size Automatically size of content

css

提问by Zach Smith

I am trying to make a h2 header for sidebar widgets but I want the width of the div class to be whatever width the content becomes. It seems I can't just set a width because those headlines with longer content then shorter content makes it break.

我正在尝试为侧边栏小部件制作一个 h2 标题,但我希望 div 类的宽度是内容变成的任何宽度。似乎我不能只设置宽度,因为那些内容较长而内容较短的标题会使其中断。

How can I simply make width stretch/change depending on the length of content there is? Any help would be greatly appreciated.

我怎样才能根据内容的长度简单地拉伸/改变宽度?任何帮助将不胜感激。

回答by Svish

As far as I know, display: inline-blockis what you probably need. That will make it seem like it's sort of inline but still allow you to use things like margins and such.

据我所知,display: inline-block这就是你可能需要的。这将使它看起来像是内联的,但仍然允许您使用边距之类的东西。

回答by rugk

If you are coming here, there is high chance width: min-contentor width: max-contentcan fix your problem. This can force an element to use the smallest or largest space the browser could choose…

如果您来这里,很有可能width: min-contentwidth: max-content可以解决您的问题。这可以强制元素使用浏览器可以选择的最小或最大空间......

This is the modern solution. Here is a small tutorial for that.

这是现代解决方案。这是一个小教程

There is also fit-content, which often works like min-content, but is more flexible. (But also has worse browser support.)

还有fit-content,它通常像 一样工作min-content,但更灵活。(但也有更差的浏览器支持。)

This is a quite new feature and some browsers do not support it yet, but browser support is growing. See the current browser status here.

这是一个相当新的功能,一些浏览器还不支持它,但浏览器的支持正在增长。在此处查看当前浏览器状态

回答by Kyle

If display: inline;isn't working, try out display: inline-block;. :)

如果display: inline;不起作用,请尝试display: inline-block;。:)

回答by Stephan Muller

h2 { display: inline }

h2 { display: inline }

回答by Delan Azabani

The best way to do this is to set display: inline;. Note, however, that in inline display, you lose access to some layout properties, such as manual height and vertical margins, but this doesn't appear to be a problem for your page.

最好的方法是设置display: inline;. 但是请注意,在嵌入式显示中,您无法访问某些布局属性,例如手动高度和垂直边距,但这对您的页面来说似乎不是问题。

回答by Yitzchak Weingarten

try to use position: absolute;

尝试使用 position: absolute;

回答by eliram9

I had faced the same issue and it got resolved by using max-width: fit content;

我遇到了同样的问题,并通过使用解决了 max-width: fit content;