簡體   English   中英

將圖像放在較小容器內的頁面寬度的一半

[英]Making an image half the page width inside of a smaller container

我正在嘗試將照片設置為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/

無需使用任何計算。

使用相對和絕對定位可實現此目的。 請參閱此處以獲取其他閱讀內容。 https://css-tricks.com/absolute-positioning-inside-relative-positioning/

您可以將任何子元素“絕對”定位為相對的父元素。

在這種情況下,將容器元素設置為具有以下position: relative; 並設置英雄形象的position: absolute; left: 0; 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以查看其工作原理。

希望這就是您要尋找的! (當然不要弄亂標記)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM