2017-10-16 43 views
1

我想中心包含在顯示設置爲表的div中的圖像。其中,我希望顯示一個圖像,該圖像應位於中心,既可以垂直放置,也可以水平放置。我已經使用margin:auto實現了水平位置,並將其設置爲display:table-cell,但它不會垂直居中。任何幫助將是巨大的中心圖像垂直div使用只有css

.overlay { height: 50%; background: red;position: fixed; 
 
top: 0; 
 
left: 0; 
 
height: 50%; 
 
width: 100%; 
 
display: table;} 
 
.swipe {height: 80px; 
 
display: table-cell; 
 
margin: auto;}
<div style="height:300px"> 
 
<div class="overlay"> 
 
    <img class="swipe" src="https://d30y9cdsu7xlg0.cloudfront.net/png/255751-200.png" />

回答

3

我會推薦給.overlay<div>一個flexbox layout而不是表。然後,你可以通過簡單地將三個規則的家長中心的形象:

.overlay { 
    display: flex; 
    align-items: center; 
    justify-content: center; 
} 

請注意,您不再需要在.swipedisplay: table-cellmargin: auto

這可以看出,在下面的例子:

.overlay { 
 
    height: 50%; 
 
    background: red; 
 
    position: fixed; 
 
    top: 0; 
 
    left: 0; 
 
    height: 50%; 
 
    width: 100%; 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: center; 
 
} 
 

 
.swipe { 
 
    height: 80px; 
 
}
<div style="height:300px"> 
 
    <div class="overlay"> 
 
    <img class="swipe" src="https://d30y9cdsu7xlg0.cloudfront.net/png/255751-200.png" /> 
 
    </div> 
 
</div>

希望這有助於! :)

頂部
0

使用填充和底部

.overlay { background: red; position: fixed; 
 
top: 0; 
 
left: 0; 
 
padding: 5% 0 5% 0; 
 
width: 100%; 
 
display: table;} 
 
.swipe {height: 80px; 
 
display: table-cell; 
 
margin: auto;}
<div style="height:300px"> 
 
<div class="overlay"> 
 
    <img class="swipe" src="https://d30y9cdsu7xlg0.cloudfront.net/png/255751-200.png" />