Html 根据文本自动调整 <div> 的大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16047491/
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 07:37:14  来源:igfitidea点击:

Resize <div> automatically based on text?

csshtmlwidthautosize

提问by lhan

I've got the following JS Fiddle to demonstrate what I'm trying to accomplish: http://jsfiddle.net/sVKU8/2/

我有以下 JS Fiddle 来演示我要完成的任务:http: //jsfiddle.net/sVKU8/2/

1) I assume this first part is easy - Is there a way to update the parent labelclass to automatically have it's widthset based on the total width of the two child <div>s so the border only wraps around the green and red <div>s? I thought setting width: autowas supposed to do that, but my CSS skills are apparently lacking.

1)我认为这第一部分很简单 - 有没有办法更新父label类以width根据两个子类的总宽度自动设置它,<div>以便边框只环绕绿色和红色<div>?我认为设置width: auto应该这样做,但我的 CSS 技能显然缺乏。

2) What I'd like to accomplish next would be to remove the widthattribute from my label-textclass and have the width set (or grow automatically, if possible) whenever I apply text to that <div>via JavaScript without text wrapping (i.e. keeping the original height of the labelclass).

2)接下来我想要完成的是width从我的label-text类中删除属性并设置宽度(或自动增长,如果可能的话)每当我<div>通过 JavaScript应用文本而不用文本换行(即保持原始高度该label班)。

I wasn't sure if I needed to try to calculate the width based on the actual text, or if there is a way to just apply the text with a width setting that will allow it to grow.

我不确定是否需要尝试根据实际文本计算宽度,或者是否有一种方法可以仅应用具有允许其增长的宽度设置的文本。

Any input or suggestions would be greatly appreciated!

任何意见或建议将不胜感激!

回答by Yann Chabot

Add this property to your css :

将此属性添加到您的 css :

 .based-on-text{
   display: inline-block;
 }

This way, the div will act like a block but will have exactly the width it needs instead of taking the whole parent level width !

这样,div 将像一个块一样,但将具有它需要的宽度,而不是采用整个父级宽度!

回答by AzDesign

click hereCSS alternative without additional JS using traditional floating elementsapproach

单击此处使用传统floating elements方法无需额外 JS 的 CSS 替代方案

回答by Lee Meador

This fiddle (Click HERE)shows using inline-blockon the div text-labeland a little JS to set the width on the outer box with the border.

这个小提琴(点击这里)显示了使用inline-blockdivtext-label和一个小 JS 来设置带边框的外框的宽度。

This is the javascript. Pretty ugly. There's probably a better way:

这是javascript。很难看。可能有更好的方法:

$(".label").css("width", 
    parseFloat( $(".label-image").css("width")) 
    + parseFloat( $(".label-text").css("width"))
);