2013-04-03 28 views
2

我試圖中心包含一個div內的桌子上的內容...但我似乎無法找出如何做到這一點上居中的內容...如何一個div

基本上我還想放一些文本旁邊的一個表,中心表和文本的網頁...

內容我試圖中心:

 <div style="background: purple; padding: 5px;"> 
      <div> 
      <table style="float: left;"> 
       <tr> 
        <th>This</th> 
        <th>is</th> 
        <th>a</th> 
        <th>test</th> 
       </tr> 
      </table> 
      </div> 
      <span style="background: yellow; margin-left: 15px; float: left;">This is a test</span> 
     </div> 

我曾嘗試:

<div style="background: red; width: 100%; text-align: center"> 
     <div style="background: purple; padding: 5px;"> 
      <div> 
      <table style="float: left;"> 
       <tr> 
        <th>This</th> 
        <th>is</th> 
        <th>a</th> 
        <th>test</th> 
       </tr> 
      </table> 
      </div> 
      <span style="background: yellow; margin-left: 15px; float: left;">This is a test</span> 
     </div> 
    </div> 

如果有人能夠告訴我我在做什麼錯誤在這裏會大大讚賞。

+0

給父'div'(即紫色背景)一個寬度,然後使用'margin:0 auto'。 – BenM

+0

我的工作代理不允許jsfiddle ...對不起:( – craig1231

回答

0

這裏是你會怎麼做:

http://jsfiddle.net/7TEqW/2/

HTML:

<div class="outer"> 
    <div class="inner"> 
     <table> 
      <tr> 
       <td>TABLE TEXT</td> 
      </tr> 
     </table> 
     <span>SPAN TEXT</span> 
    </div> 
</div> 

CSS:

.outer { 
    width: 100%; 
    text-align: center; 
} 

.inner { 
    display: inline-block; 
    margin: 0 auto; 
} 

table { 
    width: 200px; 
    float: left; 
    margin-right: 20px; 
    background: #999; 
} 

span { 
    display: inline-block; 
    width: 100px; 
    background: #ccc; 
} 
+0

這將無法與他的浮動元素 – BenM

+0

@BenM-我的壞,我已經更新了我的答案 –

+0

好吧,文本是在旁邊的表,但文本和表格不在頁面上居中... – craig1231

0

刪除float:left,並嘗試加入margin:0 auto

.wrap{ 
background: purple; padding: 5px;  
    text-align:center; 
    overflow:auto; 
    position:relative 
} 
table{ 
    background:pink; 
    margin:0 auto 
} 

span{ 
    background: yellow; margin-left: 15px; 
     margin:0 auto 
} 

DEMO

+0

我的工作代理不允許jsfiddle ...抱歉:( – craig1231

1

,如果他們是inlineinline-block您可以使用中心text-align:center元素。如果我們使用<table>上的display:inline-block來移除浮動物並將它們彼此相鄰放置,則可以使用此方法。

jsFiddle

CSS

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

HTML

<div class="wrapper" style="background: purple; padding: 5px;"> 
    <table> 
     <tr> 
      <th>This</th> 
      <th>is</th> 
      <th>a</th> 
      <th>test</th> 
     </tr> 
    </table> 
    <span style="background: yellow; margin-left: 15px;">This is a test</span> 
</div> 
+0

跨度中的文本顯示在IE中的表下,這不是我抱歉後的內容。文本需要在表格旁邊。 – craig1231

1

您可以到內部的div提供身份證說,內,外說頂格:

#outer{width:100%} 
#inner{float:none;margin:0 auto;display:table;} 

如果您發現任何問題,請告訴我!

0

將所需內容放入一個 <p style="text-align: center;"> 元素中,並且它將水平居中。