css - 限制CSS中按钮的宽度

标签 css button width limit

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>

输出类似于:

Buttons With Different Sizes

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

如果我更改 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!">

所以输出将类似于:

Buttons With Same Sizes

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

我尝试使用 CSS max-width: 来做到这一点,但按钮内的文本开始溢出。

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

在使用 button 标签时,我确实想要 input 标签的相同输出。

最佳答案

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>

关于css - 限制CSS中按钮的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48943117/

相关文章:

JavaScript/SASS : How to override default width of Google Maps API v3 Autocomplete dropdown based on width of input field?

css - 重置/删除所有浏览器(包括移动设备)的输入、选择和按钮样式

css - 带有标签的内容相关的 div

html - CSS:100% div 在移动设备上未显示为 100%

基于 URL 路径的 Javascript/jQuery 导航

html - img 元素的 CSS 网格工作得很好,但当 imgs 获得 div 包装器时会中断

forms - 如何使用 Drupal 表单 API 制作后退按钮?

css - 包装宽度不适合 2 列 50%

javascript - 隐藏/显示所有子 Div - JS

html - 如何创建一个类似于链接的 HTML 按钮?