【问题标题】:How to center my <h3> text using css?如何使用 css 使我的 <h3> 文本居中?
【发布时间】:2014-07-03 00:46:36
【问题描述】:

我有以下fiddle

HTMLjavascript 创建。如果需要,我可以将样式添加/更改为div's,但我无法更改 HTML 代码的顺序。

我知道我可以使用:

text-align: center;

但是有一个问题 :) 包含 4 张图像的 div 放在 HTML 代码中 &lt;h3&gt; 之前。由于我无法编辑HTML 订单,我想通过使用margin-top: 70px; 的图像降低DIV 问题是这对&lt;h3&gt; 中的文本有影响,而centered 不再是centered

如何解决这个问题? (使用 css3 的首选)

如果需要更改HTMLDIV's 的值以修复它,那也没关系 (我可以改变它们)

非常感谢

HTML 代码:

<div class="solitaireprefs" style="position: absolute; left: 0px; top: 0px; width: 80%; height: 80%; z-index: 100;">
<form method="get" action="">
    <div style="float: right; margin-top: 70px; display: table; vertical-align: bottom;">
        <div><img src="cardsets/test/spades1.svg" alt="Ace spades" align="bottom" style="vertical-align: bottom; width: 119px; height: 166px;"><img src="cardsets/test/clubs7.svg" alt="7 clubs" align="bottom" style="vertical-align: bottom; width: 119px; height: 166px;"></div>
        <div><img src="cardsets/test/hearts12.svg" alt="Queen hearts" align="bottom" style="vertical-align: bottom; width: 119px; height: 166px;"><img src="cardsets/test/backred.svg" alt="Card" align="bottom" style="vertical-align: bottom; width: 119px; height: 166px;"></div>
    </div>
    <h3>Options</h3>
    <h4>Images for size 119</h4>
</form>
</div>

CSS:

div.solitaireprefs {
    background-color: #fff;
    border-radius: 7px; 
    border: 1px solid #ddd;
}

div.solitaireprefs form {
    padding: 0 15px;
}

div.solitaireprefs h3 {
    background: #e9e9e9;
    margin: 0 -15px;
    padding: .7em 0;
    text-align: center;
    border-radius: 7px 7px 0 0 ; 
}

【问题讨论】:

  • 在您的问题中发布您的代码。
  • @j08691 小提琴怎么了?
  • @SmokeyPHP - 如果 jsFiddle 无法访问,那么这个问题,没有代码,就失去了它的价值。首先在问题中编码,然后是小提琴。
  • @j08691 我认为这个问题在链接可能失效的时间之后对其他人没有用处,但是好吧 - 很公平,我猜

标签: html css text center


【解决方案1】:

这个问题的真正答案是弄清楚如何正确排列 dom 元素。语义比你想象的更重要。但是由于您已经在修改视觉效果,因此最快和最肮脏的 hack 就是修复您的填充:

padding: .7em 45%;

在 div.solitairprefs h3 上 调整百分比以获得中间值,但在 h3 上缺少的左右填充总和的 10% 是选项文本出现位置之间的空间(因此相应地调整)。 而且由于您已经手动居中,您可以继续摆脱

text-align: center;

【讨论】:

  • 如果您选择 KatieK 的回复,请务必在 h3 标签中将 text-align 设置为居中。此外,使用绝对时要小心,正如 katie 所说,它会将其从文档流中取出,因此如果您希望它出现在该 div 内,则必须手动设置 div 的大小以使其“出现”这些图像在 div 内。
  • 我同意重新排列 DOM,但是脚本非常大,说实话我的 JS 技能不是那么好。所以现在我会破解它,然后再重新排列它(希望如此)
【解决方案2】:

不要在包含图像的元素上使用float:right;margin:top,而是绝对定位它。

{ position: absolute;
  top: 70px; 
  right: 10px;
}

使用绝对定位使其脱离文档流;这就是搞乱您的h3 的中心。

【讨论】:

  • 很高兴它对您有用!对于 hacky 情况,这是一个 hacky 解决方案;正如其他人所说,总体而言,使用更正确的标记会更好。
猜你喜欢
  • 2011-04-04
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
  • 2012-02-10
  • 1970-01-01
相关资源
最近更新 更多