2016-06-13 113 views
1

我試圖將徽標放在標題div的中心,其中一半徽標溢出到底部div。我有以下,但我不知道如何動態地將其設置爲居中。因爲依靠topleft值看起來會不一致。如何將背景圖片放置在div的中心位置?

.header { 
    position: relative; 
    height: 200px; 
    background-color: #000; 

    &:after { 
     z-index: 2; 
     content: ' '; 
     position: absolute; 
     left: 27%; 
     top: 60%; 
     width: 200px; 
     height: 200px; 
     background-image: url('images/logo.png'); 
    } 
} 

回答

2

您可以使用left: 50%margin-left(半寬標識的)。

.header { 
 
    background-color: #000; 
 
    position: relative; 
 
    height: 200px; 
 
} 
 

 
.header:after { 
 
    margin-left: -100px; 
 
    position: absolute; 
 
    background: #f00; 
 
    bottom: -100px; 
 
    height: 200px; 
 
    width: 200px; 
 
    content: ' '; 
 
    z-index: 2; 
 
    left: 50%; 
 
}
<div class="header"></div>

0

我可以建議Flexbox的?

居中邏輯將爲您處理,那麼您只需確保背景圖像的位置正確。

.header { 
    background-color: #000; 
    height: 200px; 
    position: relative; 

    &:after { 
     content: ''; 
     height: 100%; 
     display: flex; 
     background: url('http://i.imgur.com/9My4X1v.jpg'); 
     background-size: auto 100%; 
     background-repeat: no-repeat; 
     background-position: center; 
    } 
} 

https://jsfiddle.net/JackHasaKeyboard/9azLwx22/10/