2016-06-13 101 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/