2

我需要水平(我不在乎垂直)居中三个框(div 或 span,我不在乎),这样中间的总是居中,并且它的宽度是文本(单个单词)所需的最小宽度包含,以下列方式:

用简短的文字(一个单词):

--------------------------------------------------------------
|                                                            |
| ----------------------  ----------  ---------------------- |
| |                    |  |xxxxxxxx|  |                    | |
| |                    |  |        |  |                    | |
| ----------------------  ----------  ---------------------- |
|                                                            |
--------------------------------------------------------------

带有长文本(又是一个单词):

--------------------------------------------------------------
|                                                            |
| -----------  ------------------------------  ------------- |
| |         |  |xxxxxxxxxxxxxxxxxxxxxxxxxxxx|  |           | |
| |         |  |                            |  |           | |
| -----------  ------------------------------  ------------- |
|                                                            |
--------------------------------------------------------------

这可能吗?

我最后的诱惑远未成功(因为盒子重叠,我不想要这个):

<div style="position:relative;";>
<span style="display:block;width:100px;margin:0 auto;text-align:center;border:1px solid red"><h1>mid_text</h1>
<span style="text-align:right;position:absolute;top:0em;left:0;display:block;width:50%;float:left;border:1px solid red">left text</span>
<span style="text-align:left;position:absolute;top:0em;left:50%;display:block;float:right;width:50%;border:1px solid red">right text</span>
</span>
</div>
4

1 回答 1

7

CSS

将此添加到您的 CSS 文件中:

body
{
    padding:20px;
}
.wrapper
{
    display:table;
    width:100%;
}
.wrapper .left,
.wrapper .center,
.wrapper .right
{
    padding:0 20px;
    display:table-cell;
}
.wrapper .left,
.wrapper .right
{
    width:50%;
    background-color:#2b88f1;
}
.wrapper .center
{
    text-align:center;
    background-color:#fff;
}

HTML

这就是您的 HTML 代码的样子:

<div class="wrapper">
   <div class="left">
       left
    </div>
    <div class="center"> 
        center
    </div>
    <div class="right">
        right
    </div>
</div>

<hr>

<div class="wrapper">
   <div class="left">
       left
    </div>
    <div class="center"> 
        ceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeenter
    </div>
    <div class="right">
        right
    </div>
</div>

​ 示例:http: //jsfiddle.net/YVhLt/

于 2012-08-11T11:35:06.857 回答