使按钮宽度适合文本 [英] Make button width fit to the text

查看:80
本文介绍了使按钮宽度适合文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我摆弄这个


While I was fiddling with this 'Fancy 3D Button' example, I found that the width seemed to be hard-coded to fit the text's width.

Here is the HTML / CSS:

body {
  background-image: url(http://subtlepatterns.com/patterns/ricepaper.png)
}
a {
  position: relative;
  color: rgba(255, 255, 255, 1);
  text-decoration: none;
  background-color: rgba(219, 87, 5, 1);
  font-family: 'Yanone Kaffeesatz';
  font-weight: 700;
  font-size: 3em;
  display: block;
  padding: 4px;
  -webkit-border-radius: 8px;
  -moz-border-radius: 8px;
  border-radius: 8px;
  -webkit-box-shadow: 0px 9px 0px rgba(219, 31, 5, 1), 0px 9px 25px rgba(0, 0, 0, .7);
  -moz-box-shadow: 0px 9px 0px rgba(219, 31, 5, 1), 0px 9px 25px rgba(0, 0, 0, .7);
  box-shadow: 0px 9px 0px rgba(219, 31, 5, 1), 0px 9px 25px rgba(0, 0, 0, .7);
  margin: 100px auto;
  width: 160px;
  text-align: center;
  -webkit-transition: all .1s ease;
  -moz-transition: all .1s ease;
  -ms-transition: all .1s ease;
  -o-transition: all .1s ease;
  transition: all .1s ease;
}
a:active {
  -webkit-box-shadow: 0px 3px 0px rgba(219, 31, 5, 1), 0px 3px 6px rgba(0, 0, 0, .9);
  -moz-box-shadow: 0px 3px 0px rgba(219, 31, 5, 1), 0px 3px 6px rgba(0, 0, 0, .9);
  box-shadow: 0px 3px 0px rgba(219, 31, 5, 1), 0px 3px 6px rgba(0, 0, 0, .9);
  position: relative;
  top: 6px;
}

<link href='http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:700' rel='stylesheet' type='text/css'>

<a href="javascript:void(0);">Push me!</a>

If I remove the width property, the button would fill the page width.

Is there any way to make the button's width fit to the text, automatically?

解决方案

Remove the width and display: block and then add display: inline-block to the button. To have it remain centered you can either add text-align: center; on the body or do the same on a newly created container.

The advantage of this approach (as opossed to centering with auto margins) is that the button will remain centered regardless of how much text it has.

Example: http://cssdeck.com/labs/2u4kf6dv

这篇关于使按钮宽度适合文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆