css - 中心 CSS 按钮宽度自动

标签 css button center

我想要一个带有 width:auto;display:block; 的按钮。此按钮应以 margin:0 auto 为中心。但如果我把所有的都放在一起,那将行不通。

我做错了什么?

代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>asd</title>
</head>
<body>
I am an example content and I should be above the button. I want to have an auto width and being centered
<style type="text/css">
    .btn{
            color:black;
            font-size: 14px;
            line-height:14px;
            text-align: center;
            font-weight: bold;
            margin:0 auto;
            height:14px;
            display:block;
            cursor: pointer;
            background-color:red;
            padding:15px;
            text-decoration:none;   
    }
</style>
<a class="btn">helloworld</a>
</body>
</html>

最佳答案

你可以使用inline-block代替block:

body {
    text-align:center;
}
.btn{
   display:inline-block;
}

演示 Fiddle

另一个选项使用display:table,margin auto 可以工作:

.btn {
   display:table;
   margin: 0 auto;
}

演示 Fiddle

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

相关文章:

jquery - 滚动 div 必须滚动到底部才能选中复选框

html - CSS 文本溢出省略号在 Grid/Flex 中不起作用

java - 我想当鼠标悬停在 JButton 图像上时放大它

html - 波浪形按钮形状,里面有文字

testing - 开源或免费测试解决方案

html - 对齐图像中心,响应式 div 的底部

jquery - 哪个是移动应用程序 jquery 或 angularjs 的最佳 js 库?

CSS - 图像向下层叠且不水平对齐

swift - Ui 按钮未添加到 SkScene

html - 具有匹配水平导航的可缩放背景图像