2017-01-12 37 views
2

我想要這個結構,一個容器有flex:display,一個圖像漂浮在右邊,然後是h1和h2,我想把這些垂直和水平中心放在div的剩餘空間上。如何浮動圖像和中心標題留在空間?

這是我目前的結果。

enter image description here

樣機。

+-----------------------+ 
|      | 
|XXXX     | 
|XXXX  HELLFISH  | 
|XXXX born to die | 
|XXXX     | 
|      | 
+-----------------------+ 

這是html代碼。

div.container 
    img(src='http://vignette3.wikia.nocookie.net/simpsons/images/a/a1/Flying_Hellfish_Logo.png/revision/latest?cb=20150327234211') 
    h1 HELLFISH 
    h2 Born to die 

SCSS。

.container{ 
    display: flex; 
    width: 50%; 
    border: 1px solid red; 
    justify-content: space-between; 
    img{ 
    max-width: 300px; 
    max-height: 300px; 
    float: left; 
    } 
    h1{ 
    align-self: center; 
    margin: auto; 
    position: relative; 
    } 
    h2{ 
    align-self: center; 
    margin: auto; 
    vertical-align:middle; 
    position: relative; 
    } 
} 

該codepen。 http://codepen.io/TabaresSotelo/pen/pRyxPz

此致

回答

1
  • 包住h1h2在一個容器(它成爲圖像的兄弟撓曲項)。
  • 使用order屬性將圖像右移。您不需要使用float屬性或justify-content: space-between

.container { 
 
    display: flex; 
 
    width: 50%; 
 
    border: 1px solid red; 
 
} 
 
.nested-container { 
 
    flex: 1; /* to consume all remaining space */ 
 
    display: flex; 
 
    flex-direction: column; 
 
    justify-content: center; 
 
    align-items: center; 
 
} 
 
.container img { 
 
    max-width: 300px; 
 
    max-height: 300px; 
 
    order: 1; 
 
} 
 
h1, h2 { 
 
    margin: 0; 
 
}
<div class="container"> 
 
    <img src="http://vignette3.wikia.nocookie.net/simpsons/images/a/a1/Flying_Hellfish_Logo.png/revision/latest?cb=20150327234211" /> 
 
    <div class="nested-container"> 
 
    <h1>HELLFISH</h1> 
 
    <h2>Born to die</h2> 
 
    </div> 
 
</div>

revised codepen(編譯的代碼)

1

裹標題元素在另一個div和該div元素上設置margin: 0 autoDEMO

.container { 
    display: flex; 
    width: 50%; 
    border: 1px solid red; 
    align-items: center; 
    img { 
    max-width: 300px; 
    max-height: 300px; 
    } 
    div { 
    margin: 0 auto; 
    text-align: center; 
    } 
    h1, 
    h2 { 
    margin: 0; 
    } 
} 
.container 
    img(src='http://vignette3.wikia.nocookie.net/simpsons/images/a/a1/Flying_Hellfish_Logo.png/revision/latest?cb=20150327234211') 
    div 
    h1 HELLFISH 
    h2 Born to die