1

I have this code :

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>

enter image description here

I want to align the span to the center of TD.

I can do text-align:center but the TD is about to host future -injected-ajax -html so I don't want to touch it ( and start playing with remove/apply text-align:center ).

I could also do width:200px;display:block; and then : margin:0 auto; but I dont know its length.

So before I go to JS solution :

Question

Is there any CSS only solution to center the span ?

related jsbin : http://jsbin.com/qokizunibifa/2/edit

Royi Namir
  • 144,742
  • 138
  • 468
  • 792

2 Answers2

1

Add display: table; and margin: 0 auto; to span to horizontally center the span inside div

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;
}
<!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>
Anonymous
  • 10,002
  • 3
  • 23
  • 39
  • @RoyiNamir `display: inline-block;` doesn't work with `margin: 0 auto;` to horizontally center elements but `display: table` does works. – Anonymous Sep 28 '14 at 12:00
  • @RoyiNamir Check this out - [What, exactly, is needed for “margin: 0 auto;” to work?](http://stackoverflow.com/questions/4955122/what-exactly-is-needed-for-margin-0-auto-to-work) – Anonymous Sep 28 '14 at 12:08
  • 1
    As I said , I know that, ( meant block , not inline-block.) but then- i still need to know the width ( as i mentioned in the next line in my question) – Royi Namir Sep 28 '14 at 12:09
1

One more thing you can try is to play with trasform: translateX(-50%):

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

Demo: http://jsbin.com/fegesusuqido/1/edit

dfsq
  • 191,768
  • 25
  • 236
  • 258