1

我有我想这样显示的文本:

SOME HEADING TEXT
And then a bunch
of text under
that wrapped to
the width of the
heading.

我的意思是,我想要一个标题,下面有一些正文。我希望此块内的文本左对齐。我希望块的宽度由标题的宽度定义。然后我希望整个块以它的父级为中心。

如果我知道标题是 100 像素,我可以这样写:

<div style="width: 100px;margin:0 auto">
etc.

但我不知道标题的宽度。即使它是静态的并且我测量了它,我认为这在不同的浏览器上是不可靠的,如果用户改变他的字体大小等。

我试着说 width:0 并将  's 放入标题中。标题显示正常,但正文显示每行一个单词。

有什么有用的提示吗?

4

2 回答 2

1

您可以通过将文本绝对定位在包含的标题元素中来完成您想要做的事情。

HTML:

<h1>
    SOME HEADING TEXT

    <span>
        And then a bunch
        of text under
        that wrapped to
        the width of the
        heading.
    </span>

</h1>

CSS:

h1 { display: inline-block; position: relative; }
h1 span { text-align: center; display: block; position: absolute; font: 14px/20px Helvetica, sans-serif; }

小提琴:http: //jsfiddle.net/ftkdD/1/

*注意:我只在 Firefox 中测试过。此外,重要的是要注意,如果在元素下方设置了内容以清除高度,则元素高度可能会成为问题,您需要应用底部边距或填充,因为绝对定位的文本不会有任何影响元素的整体高度。正如你在这里看到的:http: //jsfiddle.net/ftkdD/2/ *

于 2013-04-02T17:40:59.253 回答
0

这个小提琴看起来像你想要的吗?

http://jsfiddle.net/2Rc2j/3/

CSS:

#main{
    width: 200px;
    height: 50px;
    margin: 0 auto;
    background: red;
}

#header{
    background: blue;
}

HTML:

<div id="header">
    <div id="main">

    </div>
</div>
于 2013-04-02T17:16:12.093 回答