2015-06-21 150 views
5


我想垂直居中使用高度自動的圖像,因爲我想填充水平寬度(100%)。其容器定義爲最大高度值並隱藏溢出。

HTML:垂直居中自動高度和最大高度的圖像

<figure> 
 
    <img src="http://lorempixel.com/500/500/" alt="Imagem" /> 
 
    <figcaption> 
 
    <p>Sapien elit in malesuada semper mi, id sollicitudin urna fermentum.</p> 
 
    </figcaption> 
 
</figure>

CSS:

figure { 
 
    padding: 5px 0; 
 
    max-height: 300px; 
 
    overflow-y: hidden; 
 
    position: relative; 
 
} 
 
figure>img { 
 
    width: 100%; 
 
    height: auto; 
 
    position: relative; 
 
    top: -50%; 
 
} 
 
figcaption { 
 
    bottom: 0; 
 
    position: absolute; 
 
    background-color: #1e1e1e; 
 
    color: white; 
 
    padding: 5px 10px; 
 
    font-size: 14px; 
 
    text-align: center; 
 
    width: 100%; 
 
}

回答

1

您可以使用這一招:用一些僞類中心的任何未知的內容大小:

https://css-tricks.com/centering-in-the-unknown/

關鍵是要設置之前到全尺寸的內容你需要。這將導致內容始終居中。

演示: http://codepen.io/chriscoyier/pen/gsodI

/* This parent can be any width and height */ 
.block { 
    text-align: center; 

    /* May want to do this if there is risk the container may be narrower than the element inside */ 
    white-space: nowrap; 
} 

/* The ghost, nudged to maintain perfect centering */ 
.block:before { 
    content: ''; 
    display: inline-block; 
    height: 100%; 
    vertical-align: middle; 
    margin-right: -0.25em; /* Adjusts for spacing */ 
} 

/* The element to be centered, can also be of any width and height */ 
.centered { 
    display: inline-block; 
    vertical-align: middle; 
    width: 300px; 
} 
/* This parent can be any width and height */ 
.block { 
    text-align: center; 

    /* May want to do this if there is risk the container may be narrower than the element inside */ 
    white-space: nowrap; 
} 

/* The ghost, nudged to maintain perfect centering */ 
.block:before { 
    content: ''; 
    display: inline-block; 
    height: 100%; 
    vertical-align: middle; 
    margin-right: -0.25em; /* Adjusts for spacing */ 
} 

/* The element to be centered, can also be of any width and height */ 
.centered { 
    display: inline-block; 
    vertical-align: middle; 
    width: 300px; 
} 
相關問題