2017-09-26 45 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;' –