0

我正在尝试将 div 居中并用 div 填充左右。

中心 div 将是可变长度的文本,兄弟 div 将是填充可用空间的行。这是我设想的样子:

小样

这是标记:

<div class='heading'>
  <div class='lines'></div>
  <div class='heading-link'>
    <a>Link Text</a>
  </div>
  <div class='lines'></div>
</div>
<div class='heading'>
  <div class='lines'></div>
  <div class='heading-link'>
    <a>Really Long Link Text that is still centered</a>
  </div>
  <div class='lines'></div>
</div>

这是准系统CSS:

.lines {
  display: inline-block;
  border-top: 1px solid #2c2c2c;
  border-bottom: 1px solid #2c2c2c;
}

.heading {
  text-align: center;
  display: inline-block;
}

.heading-link {
  display: inline-block;
}

关键是里面的文字.heading-link是可变长度的,我希望.linesdiv能填充左右两边的剩余空间.heading-link

我不想设置百分比宽度,.heading-link因为我不知道文本的宽度。我应该使用基于表格的布局吗?或者只是内联的div?

4

1 回答 1

1

使用 CSS 表的解决方案

以下内容可能接近您的需要。

你的HTML很好:

<div class='heading'>
    <div class='lines'></div>
    <div class='heading-link'><a>Link Text</a></div>
    <div class='lines'></div>
</div>

<div class='heading'>
    <div class='lines'></div>
    <div class='heading-link'> <a>Really Long Link Text that 
        is still centered</a></div>
    <div class='lines'></div>
</div>

Try the following CSS:

.heading {
    text-align: center;
    display: table;
    margin: 30px 0; /* for demo only */
}
.lines {
    display: table-cell;
    width: 48%; /* the exact value is not that critical... */
    border-top: 1px solid #2c2c2c;
    border-bottom: 1px solid #2c2c2c;
}
.heading-link {
    display: table-cell;
    white-space: nowrap; /* keeps the text from wrapping... */
    padding: 10px 20px; /* for demo only, as needed... */
}

How This Works

Apply display: table to the parent container .heading, and then display: table-cell to the child elements .lines and .heading-link.

I am using the table display type to take advantage of the auto-sizing features of table cells.

I am assuming that your .heading-link text will fit on one line, so I force the text to stay on a single line by using white-space: nowrap. This will force the .heading-link element to expand to contain the text. You can use padding to control the white space as needed.

For the left and right .lines elements, set the with to be something like 48%. This will keep force the left and right .lines elements to compute to the same width, half of whatever space remains after the space used up by .heading-link.

如果需要,您还可以指定总宽度.heading

演示小提琴:http: //jsfiddle.net/audetwebdesign/eyGdG/

于 2013-08-05T14:31:38.137 回答