.button {
display: block;
text-decoration: none;
color: #103d82;
background: #fff;
border: 1px solid #d2cfcd;
font-size: 1.4rem;
line-height: 1;
padding: 10px;
text-align: center;
}
div .button {
margin: 0 auto;
}
<div>
<a href="#" class="button">Link</a>
</div>
<div>
<button type="button" class="button">Button</button>
</div>
我的两个元素具有相同的CSS,但按钮居中而不是我的链接。如何处理链接的宽度与按钮的计算方式相同?是否可以在没有添加属性的情况下进行容器?
谢谢
您可以添加max-width / width属性和box-sizing:border-box
以使它们的行为相同:
.button {
display: block;
text-decoration: none;
color: #103d82;
background: #fff;
border: 1px solid #d2cfcd;
font-size: 1.4rem;
line-height: 1;
padding: 10px;
text-align: center;
max-width: 200px;
width: 100%;
box-sizing: border-box;
margin: 0 auto;
}
<div>
<a href="#" class="button">Link</a>
</div>
<div>
<button type="button" class="button">Button</button>
</div>
您也可以尝试宽度的fit-content
值,但所有broswer尚不支持,因为您可以阅读here:
这是一个不应在生产代码中使用的实验性API。
您可以在此处检查浏览器兼容性
https://developer.mozilla.org/en-US/docs/Web/CSS/width#Browser_compatibility
https://caniuse.com/#search=fit-content
.button {
display: block;
text-decoration: none;
color: #103d82;
background: #fff;
border: 1px solid #d2cfcd;
font-size: 1.4rem;
line-height: 1;
padding: 10px;
text-align: center;
width: fit-content;
box-sizing: border-box;
margin: 0 auto;
}
<div>
<a href="#" class="button">Link</a>
</div>
<div>
<button type="button" class="button">Button</button>
</div>
UPDATE
在阅读此问题之后,Centering content blocks with buttons是另一种避免使用不受支持的值的解决方案。您可以简单地将display:block
更改为display:table
,并且链接和按钮的行为都相同:
.button {
display: table;
text-decoration: none;
color: #103d82;
background: #fff;
border: 1px solid #d2cfcd;
font-size: 1.4rem;
line-height: 1;
padding: 10px;
text-align: center;
box-sizing: border-box;
margin: 0 auto;
}
<div>
<a href="#" class="button">Link</a>
</div>
<div>
<button type="button" class="button">Button</button>
</div>
您可以做的是将display: block
更改为display: inline-block
,然后将text-align: center
添加到他们的父母而不是margin: 0 auto
,如下所示:
.button {
display: inline-block;
text-decoration: none;
color: #103d82;
background: #fff;
border: 1px solid #d2cfcd;
font-size: 1.4rem;
line-height: 1;
padding: 10px;
text-align: center;
}
div {
text-align: center;
}
<div>
<a href="#" class="button">Link</a>
</div>
<div>
<button type="button" class="button">Button</button>
</div>
试试这个:
* {
box-sizing: border-box;
}
div {
width: 100px;
position: relative;
margin: 0 auto;
}
.button {
width: 100%;
display: block;
text-decoration: none;
color: #103d82;
background: #fff;
border: 1px solid #d2cfcd;
font-size: 1.4rem;
text-align: center;
padding: 10px;
}
<div>
<a href="#" class="button">Link</a>
</div>
<div>
<button type="button" class="button">Button</button>
</div>