2014-12-07 117 views
2

我有一個小問題與CSS居中:/
我有2個或更多的div在同一行,我會他們的寬度是相等的彼此。 因此,如果有2個div,那麼1.和2. div必須具有相同的面積(50%和50%),這些div應居中。如何將2個或更多div放在同一行上? (css)

我有一個代碼在下面,但它不工作。

<div class="main"> 
    <div class="xy">First</div> 
    <div class="xy">Second</div> 
</div> 

CSS:

.xy { 
    display: inline; 
    margin: auto; 
} 
.main { 
    height: 100%; 
    width: 100%; 
    background-color: #c0c0c0; 
} 

回答

1

一個簡單的解決方案是使用display: tabledisplay: table-cell,如:

.xy { 
 
    display: table-cell;/*set display to table-cell*/ 
 
    width: 50%;/*set the width to 50%*/ 
 
} 
 
.main { 
 
    height: 100%; 
 
    width: 100%; 
 
    background-color: #c0c0c0; 
 
    display: table;/*set display to table*/ 
 
}
<div class="main"> 
 
    <div class="xy">First</div> 
 
    <div class="xy">Second</div> 
 
</div>

如果你想要的文字是中心也可以加text-align: center.xy

.xy { 
 
    display: table-cell; 
 
    width: 50%; 
 
    text-align: center;/*add text-align center*/ 
 
} 
 
.main { 
 
    height: 100%; 
 
    width: 100%; 
 
    background-color: #c0c0c0; 
 
    display: table; 
 
}
<div class="main"> 
 
    <div class="xy">First</div> 
 
    <div class="xy">Second</div> 
 
</div>

+0

很高興我幫你:D – 2014-12-07 19:23:33

0
.xy { 
    display: inline-block; 
    margin: auto; 
    widht: 50% 
} 

切換到內聯塊,並給它以%的寬度。

相關問題