2017-09-26 76 views
-1

我想使用表格爲圖表製作圖例。我創建了一個示例來展示問題。使表格內容居中但左對齊

https://jsfiddle.net/s3mf64gq

<div class="container"> 
    <div class="row"> 
    <div class="panel col-md-12"> 
     <table class="table borderless"> 
     <tbody> 
      <tr> 
      <td> 
       Jane - Software Engineer 
      </td> 
      <td> 
       John - Senior Marketing Executive 
      </td> 
      </tr> 
      <tr> 
      <td> 
       Teddy - CEO 
      </td> 
      <td> 
       James - Lecturer 
      </td> 
      </tr> 
     </tbody> 
     </table> 
    </div> 
    </div> 
</div> 

我有2個要求:

  1. 所有的項目都必須靠左對齊,
  2. 容器必須是中心父

如何解決它?我卡住了。

挑戰是項目的長度不相等,否則我會簡單地在td上做文本對齊中心,然後解決。

+0

什麼是父母是什麼樣子?你如何設置容器的寬度?你有沒有考慮過使用flexbox而不是table? –

+1

在你的小提琴中,容器div居中,你的td物品左對齊,我不明白你想要什麼,請你可以多解釋一下 – Pete

+2

我不明白這個問題。什麼是應該左對齊,什麼是應該居中? – Jay

回答

0

由於.table類有100%預定width,則需要將其設置爲auto所以<table>將其內容的大小。

然後加入margin: 0 auto它將水平居中。

.table { 
    margin: 0 auto;   /* horizontally center */ 
    width: auto;    /* reset the built in value of 100% */ 
} 

Updated fiddle

棧片斷

<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"> 
 

 
<style> 
 
/* Latest compiled and minified CSS included as External Resource*/ 
 

 
/* Optional theme */ 
 

 
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css'); 
 

 
body { 
 
    margin: 10px; 
 
    padding: 0; 
 
} 
 

 
.panel { 
 
    background: #eee; 
 
} 
 

 
.borderless td, 
 
.borderless th { 
 
    border: none !important; 
 
} 
 

 
.table { 
 
    margin: 0 auto; 
 
    width: auto; 
 
} 
 
</style> 
 

 
<div class="container"> 
 
    <div class="row"> 
 
    <div class="panel col-md-12"> 
 
     <table class="table borderless"> 
 
     <tbody> 
 
      <tr> 
 
      <td> 
 
       Jane - Software Engineer 
 
      </td> 
 
      <td> 
 
       John - Senior Marketing Executive 
 
      </td> 
 
      </tr> 
 
      <tr> 
 
      <td> 
 
       Teddy - CEO 
 
      </td> 
 
      <td> 
 
       James - Lecturer 
 
      </td> 
 
      </tr> 
 
     </tbody> 
 
     </table> 
 
    </div> 
 
    </div> 
 
</div>

+0

非常感謝,但我必須使用左右填充我的td。想象一下,我有不同的寬度不同的容器塊,你會怎麼做? –

+0

@CeciliaChan我沒有改變任何填充左邊或右邊,所以你能解釋你的意思嗎? ...和不同的容器寬度不同,請張貼更新的小提琴,展示如何看起來像我可以建議一個解決方案。 – LGSon

+0

就像你的表是在2個不同的容器中,有'col-md-4'和'col-md-8'類。它不會很好地傳播,如果我像'padding:0 20px;' –