将图像垂直居中放置在弹性项目中的锚标记内

时间:2017-02-25 11:58:25

标签: css html5 flexbox

我试图将图像置于flex布局的单元格中,并将flex-direction设置为row,行中每个单元格的高度等于该行图像的最大高度。

该行的其他较小图像应相对于高度居中。

尝试以垂直对齐和边距为中心,似乎不起作用。

function getRandomSize(min, max) {
 return Math.round(Math.random() * (max - min) + min);
}

for (var i = 0; i < 10; i++) {
var width = getRandomSize(200, 400);
var height =  getRandomSize(200, 400);
$('#photos').append('<a style="display:inline-block" href="http://www.google.com" ><img src="http://www.lorempixel.com/'+width+'/'+height+'/cats" alt="pretty kitty"></a>');
}
        #photos{
            display: flex; /* Initializing a flexbox formatting context */
            flex-flow : row wrap ;/*flex-direction and flex-wrap*/
        }

        #photos a:nth-child(odd){
            flex : 0 0 20%;
            background-color: aqua;
            border:1px solid black;
            height:auto;
        }

        #photos a:nth-child(even){
            flex : 0 0 20%;
            background-color: red;
            border:1px solid yellow;
            height:auto;
        }



        #photos img{
            width : 100%;
            padding: auto;
            vertical-align: middle;
        }


        
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="photos">
    </div>

这是jsfiddle

的链接

https://jsfiddle.net/k3gbquda/

这可能吗?有人可以提出解决方案吗? 感谢

3 个答案:

答案 0 :(得分:2)

“A”元素应该是嵌套的flexbox而不是内联块。

    #photos {
        display: flex; /* Initializing a flexbox formatting context */
        flex-flow: row wrap ;/*flex-direction and flex-wrap*/
    }

    #photos a {
        flex : 0 0 20%;
        display: flex;
        align-items: center;
    }

    #photos a:nth-child(odd) {
        background-color: aqua;
        border:1px solid black;
    }

    #photos a:nth-child(even) {
        background-color: red;
        border:1px solid yellow;
    }

    #photos img {
        width : 100%;
        height: auto;
        display: block;
    }

请参见修改过的小提琴:https://jsfiddle.net/1wpgo45t/7/

答案 1 :(得分:0)

有一个名为align-items的flexbox属性,这正是您正在寻找的。

align-items: center;

答案 2 :(得分:0)

试试这个

#photos a:nth-child(odd){
        flex : 0 0 20%;
        background-color: aqua;
        border:1px solid black;
        height:auto;
        margin:auto;
}
相关问题