【问题标题】:Limit Width Of The Buttons In CSS限制 CSS 中按钮的宽度
【发布时间】:2018-08-03 05:31:45
【问题描述】:

CSS:

.btn { 
background: #53A2FF;
border: 2px solid transparent;
color: #eee;
font-weight: bold;
padding: 9px 15px;
outline: none;
transition: 0.5s all;
-webkit-transition: 0.5s all;
-moz-transition: 0.5s all;
-o-transition: 0.5s all;
-ms-transition: 0.5s all;
}
.btn:hover { 
border: 2px solid #000;
background: transparent;
color: #000;
}   

HTML:

<button class="btn">Hello Over There!</button>
<br><br>
<button class="btn">This Button Has Too Much Text, That's Why It Is Bigger!</button>
<br><br>
<button class="btn">Hello Over There! This Is The Third Button!</button>

输出将类似于:

每个按钮的大小取决于字母的数量。

如果我更改 HTML 并做这样的事情。

<input class="btn" value="Hello Over There!">
<br><br>
<input class="btn" value="This Button Has Too Much Text, That's Why It Is Bigger!">
<br><br>
<input class="btn" value="Hello Over There! This Is The Third Button!">

所以输出将类似于:

每个按钮的大小将相同。但是input标签主要用于HTML表单,用它们来制作链接根本不是一个好主意!

我尝试使用 CSS max-width: 执行此操作,但按钮内的文本开始溢出。

如果我想使用button 标签而不是input 标签,并且如果我想限制按钮的宽度,那么我应该使用哪个 CSS 代码?

在使用button 标记时,我完全想要input 标记的相同输出。

【问题讨论】:

  • @TemaniAfif 需要编辑什么?这不像
    是 HTML 中的错误之类的。
  • 我认为这不是改变它的充分理由。根据规范,斜线是可选的,那么为什么不能保留它们呢?此外,我们怎么知道 OP 的环境是 HTML 而不是 XHTML?

标签: css button width limit


【解决方案1】:
.btn { 
display: inline-block;
font-size: 12px;
background: #53A2FF;
border: 2px solid transparent;
color: #eee;
font-weight: bold;
padding: 3px 2px;
width: 250px;
outline: none;
transition: 0.5s all;
-webkit-transition: 0.5s all;
-moz-transition: 0.5s all;
-o-transition: 0.5s all;
-ms-transition: 0.5s all;
}
.btn:hover { 
border: 2px solid #000;
background: transparent;
color: #000;
} 

如果它适合你,试试这个。通过宽度属性,你可以在 css 中指定按钮的宽度

【讨论】:

    【解决方案2】:

    max-width 是正确的,但您还需要 1) 使用 white-space 确保文本不换行,以及 2) 使用 overflow 隐藏无关字符。

    .btn {
      background: #53A2FF;
      border: 2px solid transparent;
      color: #eee;
      font-weight: bold;
      padding: 9px 15px;
      outline: none;
      transition: 0.5s all;
      -webkit-transition: 0.5s all;
      -moz-transition: 0.5s all;
      -o-transition: 0.5s all;
      -ms-transition: 0.5s all;
      /* so these are new: */
      max-width:20em;
      white-space:nowrap;
      overflow:hidden;
    }
    
    .btn:hover {
      border: 2px solid #000;
      background: transparent;
      color: #000;
    }
    <button class="btn">Hello Over There!</button>
    <br><br>
    <button class="btn">This Button Has Too Much Text, That's Why It Is Bigger!</button>
    <br><br>
    <button class="btn">Hello Over There! This Is The Third Button!</button>

    【讨论】:

    • 另外,您可以使用title标签在悬停时显示原文。
    猜你喜欢
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 2014-01-21
    • 2016-08-11
    • 2014-06-01
    • 1970-01-01
    • 2020-03-31
    相关资源
    最近更新 更多