如何像按钮元素一样设置div的样式?
我注意到,当使用< button>< / button>
元素时,浏览器自然会假定您想将内联内容居中,并且该元素是可点击的。是否有可能让div通过CSS以相同的方式表现?我浏览了UA样式表,看是否可以解决这个问题,但没有任何方法使它垂直居中。
I've noticed that when using the <button></button>
element, the browsers will naturally assume that you want to center the inline content, and that the element is clickable. Is it possible to have a div behave in the same way through css? I went through the UA-stylesheet to see if I could figure it out, but nothing made it center it vertically.
我知道获得相同结果的唯一其他方法是2 divs。一个具有 display:table
的包装器,一个具有 display:table-cell
和 vertical的div -align:middle
。
The only other way i know to get the same result is with 2 divs. One wrapper with display: table
, and a div with display: table-cell
and vertical-align: middle
.
但这会创建一个额外的div。仅用一个元素就能实现相同的行为吗?
But that creates an extra div. Is it possible to achieve the same behaviour with just one element?
谢谢。
http://jsfiddle.net/8Sj4A/3/ -这确实垂直和水平居中(只需添加 text- align:center;
到原始答案)
http://jsfiddle.net/8Sj4A/3/ - this does center vertically and horizontally (just added text-align: center;
to the originally answer)
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);
}