2016-09-22 54 views
1

我是造型的数字。中心容器和使用负余量

我想这样,当图像比文字栏小,这个数字缩小到它的大小和中心,使之为我使用:

div { 
 
    width: 20em; 
 
    margin: 0 auto; 
 
    background-color: #f8f8f8; 
 
} 
 
figure { 
 
    display: table; 
 
    margin: 1rem auto; 
 
    padding: 2rem 2rem; 
 
    background-color: #eee; 
 
} 
 
figure img { 
 
    max-width: 100%; 
 
    margin: 0 auto; 
 
}
<div><figure> 
 
    <img src="https://placehold.it/100x100" alt="100x100 placeholder"> 
 
</figure> 
 
<figure> 
 
    <img src="https://placehold.it/400x100" alt="400x100 placeholder"> 
 
</figure></div>

问题是,当图像是列的大小时,我希望图形在列外出血。对于我通常使用:

div { 
 
    width: 20em; 
 
    margin: 0 auto; 
 
    background-color: #f8f8f8; 
 
} 
 
figure { 
 
    display: table; 
 
    margin: 1rem -2rem; 
 
    padding: 2rem 2rem; 
 
    background-color: #eee; 
 
} 
 
figure img { 
 
    max-width: 100%; 
 
    margin: 0 auto; 
 
}
<div><figure> 
 
    <img src="https://placehold.it/100x100" alt="100x100 placeholder"> 
 
</figure> 
 
<figure> 
 
    <img src="https://placehold.it/400x100" alt="400x100 placeholder"> 
 
</figure></div>

,但该解决方案消除了margin: auto;中心

我会很感激CSS唯一的解决办法,但js和jQuery将做,如果没有其他way

回答

2

figure设置为inline-table并将text-align:center应用于父级。

body { 
 
    background: lightgreen; 
 
} 
 
div { 
 
    width: 20em; 
 
    margin: 0 auto; 
 
    background-color: #f8f8f8; 
 
    background: cornflowerblue; 
 
    text-align: center; 
 
} 
 
figure { 
 
    display: inline-table; 
 
    margin: 1rem -2rem; 
 
    padding: 2rem 2rem; 
 
    background-color: #eee; 
 
} 
 
figure img { 
 
    max-width: 100%; 
 
    margin: 0 auto; 
 
}
<div> 
 
    <figure> 
 
    <img src="https://placehold.it/100x100" alt="100x100 placeholder"> 
 
    </figure> 
 

 
    <figure> 
 
    <img src="https://placehold.it/400x100" alt="400x100 placeholder"> 
 
    </figure> 
 
</div>

+0

大概不会令图使用居中文本的所有兄弟和侄子(?)?有没有办法让它不可继承? –

+1

不,你必须覆盖它的任何儿童等,但应该是一个足够简单的CSS选择器 - https://jsfiddle.net/mhag64uy/ –

+0

愚蠢的我,我想我不得不覆盖每一个儿童... –