我在使用 CSS 实现我想要的功能时遇到了问题:
样式表:
/* firstHeading */
.firstHeading {
background-color:#9f9f2c;
padding:10px;
font-family: 'BankGothic Md BT', Machine;
font-variant: small-caps;
text-transform: capitalize;
font-weight: normal;
font-size: x-large;
color:#ffff95;
border-style: ridge;
border-width: 2px;
border-color: gray;
border-collapse: separate;
border-spacing: 2px;
margin-top:0;
margin-bottom:10px;
margin-left:auto;
margin-right:auto;
text-align: center;
display: inline-block;
*zoom: 1;
*display: inline;
}
HTML:
<h1 id="firstHeading" class="firstHeading">List title</h1>
挑战:这看起来很有效,完全符合我的要求,但现在我需要在页面上水平(而不是垂直)居中,同时保持边框和背景填充颜色的大小与它们的大小相似 - 纯粹在 CSS 中。 “列表标题”可以很短或很长 - 动态宽度。
如您所见,我尝试将左右边距设置为自动。在这一点上,我看到的大多数建议都建议设置宽度,例如“width:100%;”。当我这样做时,它在整个页面居中,但它确实拉伸(stretch)了背景“ block ”,我希望它更合身。我阅读的其他建议也使它不是动态宽度,然后我遇到了换行问题。
我也无法在 HTML 中包装另一个 div:它已经包装在一个名为“content”的 div 中 - HTML 是从 MediaWiki 页面生成的代码。如果我们将“内容”居中,那么我们居中的不仅仅是标题,还有页面内容的其余部分,我希望它是左对齐的。
建议?
最佳答案
您正在尝试使 inline-block
居中,这实际上只能通过在父元素上设置 text-align: center;
来完成。
您可以先将 h1
设置为 display: block;
和 text-align: center;
。之后,您可以在 h1
中使用 span
作为背景/边框效果。这样做将使跨度位于 h1 标签的中心,而跨度的宽度不会向外扩展。
HTML:
<h1 id="firstHeading" class="firstHeading">
<span>List title</span>
</h1>
CSS:
/* firstHeading */
.firstHeading {
margin-top:0;
margin-bottom:10px;
margin-left:auto;
margin-right:auto;
text-align: center;
display: block;
*zoom: 1;
text-align: center;
}
.firstHeading span {
background-color:#9f9f2c;
padding:10px;
font-family: 'BankGothic Md BT', Machine;
font-variant: small-caps;
text-transform: capitalize;
font-weight: normal;
font-size: x-large;
color:#ffff95;
border-style: ridge;
border-width: 2px;
border-color: gray;
border-collapse: separate;
border-spacing: 2px;
}
关于html - 水平居中 H1/Class,动态宽度和收缩以适合边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19054129/