如何像按钮元素一样设置 div 样式?

问题描述 投票:0回答:6

我注意到,当使用

<button></button>
元素时,浏览器自然会假设您想要将内联内容居中,并且该元素是可单击的。是否可以通过 css 让 div 以相同的方式表现?我浏览了 UA 样式表,看看是否能弄清楚它,但没有任何东西使它垂直居中。

我知道获得相同结果的唯一其他方法是使用 2 个 div。一个带有

display: table
的包装器,以及一个带有
display: table-cell
vertical-align: middle
的 div。

但这会创建一个额外的 div。仅用一个元素是否可以实现相同的行为?

谢谢。

html css button
6个回答
14
投票

http://jsfiddle.net/8Sj4A/3/ - 这确实垂直和水平居中(刚刚在原始答案中添加了

text-align: center;

div {
    display:inline-block;
    color:#444;
    border:1px solid #CCC;
    background:#DDD;
    box-shadow: 0 0 5px -1px rgba(0,0,0,0.2);
    cursor:pointer;
    vertical-align:middle;
    max-width: 100px;
    padding: 5px;
    text-align: center;
}
div:active {
    color:red;
    box-shadow: 0 0 5px -1px rgba(0,0,0,0.6);
}

2
投票

您不需要多个 div,请检查这个 JSFiddle,它是一个外观和行为都像按钮的 DIV。

HTML:

<div class='btn'>
  this looks like a button
</div>

CSS:

.btn{
    display: inline-block;
    padding: 6px 12px;
    margin-bottom: 0;
    font-size: 14px;
    font-weight: 400;
    line-height: 1.42857143;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border: 1px solid transparent;
    border-radius: 4px;
    text-decoration: none;

    color: #333;
    background-color: #fff;
    border-color: #ccc;
}

如果您希望按钮实际链接到某些内容(表现得像链接),只需将 HTML 更改为:

<a href='test.html' class='btn'>
  this looks like a button
</a>

如果您使用 bootstrap,则不必定义 .btn 类,它已包含在其中。


1
投票

也许您问错了问题。

为您的按钮指定一个类,然后确保内联内容的样式符合您的要求可能会更简单。

任何可以放入 DIV 中的内容,都应该能够放入按钮中。


1
投票

您可以通过在每一侧添加相同数量的填充来使 div 的内容居中。

padding:2px 10px;

这会向顶部和底部添加 2px,向左和右侧添加 10px,从而使内容在 div 中居中。

我还设计了 div 的其余部分,使其外观和行为类似于

button
。外观基于 Firefox 的默认值
<button>

http://jsfiddle.net/evSb5/2/


0
投票

这和按钮式输入一模一样

#divbut {
    display: inline-block;
    color: #444;
    background: #232323;
    cursor: pointer;
    padding: 5px;
    text-align: center;
    width: 200px;
    border-top: solid 2px #767676;
    border-left: solid 2px #767676;
    border-right: 2px #777171;
    border-bottom: 2px #777171;
    border-style: outset;
    box-sizing: content-box;
}

#divbut:active {
    color: green;
    border-top: 2px solid #777171;
    border-left: 2px solid #777171;
    border-right: solid 2px #767676;
    border-bottom: solid 2px #767676;
    border-style: inset;
}

<div id="divbut" class="center">
    <span class="unselectable">Button</span>
</div>

-2
投票

CSS:

div.button {
  display:inline-block;
  -webkit-appearance:button;
  padding:3px 8px 3px 8px;
  font-size:13px;
  position:relative;
  cursor:context-menu;
}

html:

<div role="button" class="button">Press Me!</div>

这让你尽可能接近真正的按钮。

对于 Chrome 以外的任何其他版本:查找

appearance
。实际上,只需使用 Chrome...:)

© www.soinside.com 2019 - 2024. All rights reserved.