jquery - CSS - 根据包含的文本宽度更改 DIV 宽度

标签 jquery html css text width

最近我发现this good-looking example用于为按钮实现某种 Material 设计。

每个按钮都由几个类组成,因此只需修改其中一个就可以对其进行自定义。我的问题是,我希望按钮随着它们包含的文本改变宽度。

简而言之,一个“按钮”是这样创建的:

<div class="button flat">
    <div class="center" fit><b>NOT NOW</b></div>
    <!--A custom tag, it came with the [original example][2]-->
    <paper-ripple fit></paper-ripple>
</div>

我需要根据内部 div(类为“center”)包含的文本更改父 div 的宽度(类为“button”和“flat”的类)。我尝试了几种仅使用 CSS 的方法,但作为新手,我没有找到获取内部 div 文本的“实际宽度”或“包装它”的方法。所以后来我找到了一个使用 jQuery/Javascript 的解决方案。 Here's the fiddle使用该解决方案。

但是,我的问题是是否有办法做类似 this in the JSFiddle 的事情,但仅使用 HTML 和 CSS。

提前谢谢你。

最佳答案

您可以尝试在 .button 类的宽度属性上使用 CSS 最小宽度规则

.button {
      display: inline-block;
      position: relative;
      min-width:60px;
      width:auto;
      height: 32px;
      line-height: 32px;
      border-radius: 2px;
      font-size: 0.9em;
      background-color: #fff;
      color: #646464;
    }

关于jquery - CSS - 根据包含的文本宽度更改 DIV 宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27786692/

相关文章:

javascript - 动态添加复选框时,用于从组中选择一个复选框的 JQuery 脚本不起作用

html - 带 Div 的导航栏

jquery - asp.net web 表单的 super 菜单

javascript - 如何在javascript AJAX中从php获取两个id值

jquery - Royalslider 宽度问题

javascript - 使用 <a name> 时 Accordion 不会打开

javascript - JS - 解析\n 和其他对象到相关 HTML

html - 使包装器 div 的宽度相对于内容

css - 组合字符串和变量值以访问现有变量

html - 在视频上叠加图像时如何保持图像背景透明度?