Keep the middle item centered when side items have different widths

后端 未结 7 1197
长情又很酷
长情又很酷 2020-11-22 17:09

Imagine the following layout, where the dots represent the space between the boxes:

[Left box]......[Center box]......[Right box]

7条回答
  •  无人及你
    2020-11-22 17:57

    you can also use this simple way to reach exact center alignment for middle element :

    .container {
        display: flex;
        justify-content: space-between;
    }
    
    .container .sibling {
        display: flex;
        align-items: center;
        height: 50px;
        background-color: gray;
    }
    
    .container .sibling:first-child {
        width: 50%;
        display: flex;
        justify-content: space-between;
    }
    
    .container .sibling:last-child {
        justify-content: flex-end;
        width: 50%;
        box-sizing: border-box;
        padding-left: 100px; /* .center's width divided by 2 */
    }
    
    .container .sibling:last-child .content {
        text-align: right;
    }
    
    .container .sibling .center {
        height: 100%;
        width: 200px;
        background-color: lightgreen;
        transform: translateX(50%);
    }
    
    

    codepen: https://codepen.io/ErAz7/pen/mdeBKLG

提交回复
热议问题