div内的水平对齐SPAN(动态长度,没有文本对齐)?

时间:2014-09-28 11:53:05

标签: html css

我有这段代码:



table
{
  border:solid 2px black;
  width:100%; /*must*/
}
td
{
  border:solid 2px red;
  padding:5px;
}

span
{
   border:solid 2px green;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<table>
    <tr>
       <td>
	    <span  >There's already existing policy for : fugfuj tyutyuty</span>
      </td>
  </tr>
</body>
</html>
&#13;
&#13;
&#13;

enter image description here

我想将spanTD的中心对齐。

我可以text-align:center,但TD即将托管未来-injected-ajax -html,所以我不想触摸它(并开始玩remove / apply {{ 1}})。

我也可以text-align:center然后:width:200px;display:block;,但我不知道它的长度。

所以在我去JS解决方案之前:

问题

是否有任何CSS唯一的解决方案来居中?

相关的jsbin:http://jsbin.com/qokizunibifa/2/edit

2 个答案:

答案 0 :(得分:1)

display: table;margin: 0 auto;添加到span,使spandiv水平居中

&#13;
&#13;
table {
    border:solid 2px black;
    width:100%; /*must*/
}
td {
    border:solid 2px red;
    padding:5px;
}
span {
    border:solid 2px green;
    display: table;
    margin: 0 auto;
}
&#13;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <table>
    <tr>
      <td>
        <span>There's already existing policy for : fugfuj tyutyuty</span>
      </td>
    </tr>
  </table>
</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以尝试的另一件事是使用trasform: translateX(-50%)

span {
    border:solid 2px green;
    position: relative;
    display: inline-block;
    left: 50%;
    transform: translateX(-50%);
}

演示:http://jsbin.com/fegesusuqido/1/edit