0

我在用 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%;”。当我这样做时,它在页面上居中,但它确实拉伸了背景“块”,我希望它更合身。我阅读的其他建议也使它不是动态宽度,然后我遇到了换行问题。

我也不能在 HTML 中包装另一个 div:它已经包装在一个名为“内容”的 div 中——HTML 是从 MediaWiki 页面生成的代码。如果我们将“内容”居中,我们将不仅仅是标题,而是页面内容的其余部分,我希望它是左对齐的。

建议?

4

2 回答 2

0

您正在尝试使 居中inline-block,这实际上只能通过text-align: center;在父元素上进行设置来完成。

您可以先将h1todisplay: block;text-align: center;. 之后,您可以使用span内部作为h1背景/边框效果。这样做将允许跨度位于 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;
}

示例:http: //jsfiddle.net/s2kjY/

于 2013-09-27T15:10:14.563 回答
0

元素必须具有明确的宽度设置,以便使用自动边距将它们水平居中。如果您正在使用,display: inline-block那么您应该能够将其与text-align: center.

于 2013-09-27T15:17:09.123 回答