将div对齐到跨度

时间:2014-02-25 20:14:50

标签: html css3

我希望能够将div与跨度对齐。例如:

<div style="some magic">foo bar<div> 
<p>this is a random text with <span class="stressed">stressed phrase</span> in it</p>

结果如下:

                              foo bar
this is a random text with stressed phrase in it

其中div的内容以span中的文本为中心。

1 个答案:

答案 0 :(得分:3)

演示:http://jsfiddle.net/rJXE3/3/

HTML

<p>this is a random text with <span class="stressed"><span class="somemagic">foo bar</span>stressed phrase</span> in it</p>

CSS

.somemagic {
    display: inline-block;
    position: absolute;
    width: 100%;
    height: 100%;
    text-align: center;
    bottom: 100%;
    white-space: nowrap;
    margin-left: -25px;       // if stressed text is smaller you need a negative margin
                              // either set manually if text size is known or calculated
}                             // and set with javascript
.stressed {
    position: relative;
}

您可能还需要为“p”(或额外的换行符)添加一个边距,以便上面的任何元素都不会被“somemagic”文本覆盖。

更新2

演示:http://jsfiddle.net/rJXE3/4/

我找到了另一个选项如何设置CSS(并且不需要javascript)

.somemagic {
    display: inline-block;
    position: absolute;
    width: 300%;
    height: 100%;
    text-align: center;
    bottom: 100%;
    white-space: nowrap;
    left: -100%;
}
.stressed {
    position: relative;
}