html - 水平居中 H1/Class,动态宽度和收缩以适合边框

标签 html css

我在使用 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;
}

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

关于html - 水平居中 H1/Class,动态宽度和收缩以适合边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19054129/

相关文章:

html - 使静态页面响应

javascript - Bootstrap 汉堡包在切换后不显示列表元素

css - 如何防止一个 div 影响另一个 Bootstrap 表单元素的垂直位置?

javascript - ReactJS 无法识别

php - CSS/JS 将 <td> 着色为条形图?

javascript - 从 JS 中的输入标签获取值,无需 id 或 HTML 控件

html - TH的AngularJS ng-repeat组

html - 泄漏 margin : unexpected offset due to nested DIVs

html - 禁用同位素中元素的绝对位置

javascript - 单击按钮时更改按钮的背景颜色