2016-12-01 57 views
0

我試圖將照片設置到50vw(半頁面寬度)的一半,頁面寬度內的形象,始終與屏幕左對齊,只使用CSS - 沒有重組的HTML。我希望Flexbox的另一半在容器內保持居中。從本質上講,如果你的屏幕寬度爲1600px,Nick Cage應該從左邊的0px開始,延伸到800px(中心),然後.hero-text應該從800px開始並在1400px結束,因爲它保持侷限於1200px寬度的容器。製作一個小容器

我已經評論了一條我認爲是關鍵的線,但是我無法正確地計算數學。無論分辨率如何,我只需要將圖像偏移到屏幕的左邊緣即可。

.container { 
 
    width: 100%; 
 
    border: 1px solid blue; 
 
    height: 500px; 
 
} 
 
.inner { 
 
    width: 1200px; 
 
    height: 100%; 
 
    margin: 0 auto; 
 
    border: 1px solid red; 
 
} 
 
.hero { 
 
    width: 100%; 
 
    height: 100%; 
 
    border: 1px solid green; 
 
    display: flex; 
 
    flex-direction: row; 
 
    align-items: center; 
 
    justify-content: center; 
 
    text-align: center; 
 
} 
 
.hero > div { 
 
    width: 50%; 
 
} 
 
.hero-image { 
 
    width: 50vw; 
 
    height: 100%; 
 
    /* margin-left: calc((100vw - 1200px) * -1); */ 
 
    background: url('https://www.placecage.com/c/500/400'); 
 
    background-repeat: no-repeat; 
 
    background-size: cover; 
 
}
<div class="container"> 
 
    <div class="inner"> 
 
    <div class="hero"> 
 
     <div class="hero-image"> 
 
     </div> 
 
     <div class="hero-text">Here is Nick Cage, everybody! 
 
     </div> 
 
    </div> 
 
    </div> 
 
</div>

https://jsfiddle.net/cqu6xf90/1/

回答

1

無需使用任何計算。

使用相對的&絕對定位來實現這一點。 請參閱這裏瞭解更多信息。 https://css-tricks.com/absolute-positioning-inside-relative-positioning/

您可以用相對父定位任何子元素「絕對」。

在這種情況下,設置容器元素有position: relative; &設置的英雄形象有position: absolute; left: 0;實際上將設置將其放置在元素的左側。

完整的CSS

.container { 
    width: 100%; 
    border: 1px solid blue; 
    height: 500px; 
/* Relative Parent */ 
    position: relative; 
} 

.inner { 
    width: 1200px; 
    height: 100%; 
    margin: 0 auto; 
    border: 1px solid red; 
} 

.hero { 
    width: 100%; 
    height: 100%; 
    border: 1px solid green; 
    display: flex; 
    flex-direction: row; 
    align-items: center; 
    justify-content: center; 
    text-align: center; 
} 
.hero > div { 
    width: 50%; 
} 
.hero-text { 
/* Margin to place the text div */ 
    margin-left: 50%; 
} 
.hero-image { 
/* Positions the hero image where you want it */ 
    position: absolute; 
    left: 0; 
    width: 50vw; 
    height: 100%; 
    /* margin-left: calc((100vw - 1200px) * -1); */ 
    background: url('https://www.placecage.com/c/500/400'); 
    background-repeat: no-repeat; 
    background-size: cover; 
} 

看看這個codepen http://codepen.io/anon/pen/NbwVmy看到它的工作。

希望這是你在找什麼! (當然不會搞亂標記)

相關問題