簡體   English   中英

CSS從不同方向更改元素寬度

[英]CSS change element width from different direction

我有一個div,其中包含一個圖像元素,其設置如下:

<div id="container">
  <img src="cat.jpg"/>
</div>

和CSS:

#container {
  width: 150px;
  height: 200px;
}

#container img {
  width: 200px;
  height: 200px;
  overflow: none;
}

目前容器寬度小於img寬度,這意味着我想要的圖像的右側部分被裁剪掉了。 但是,我希望將圖像的左側部分切掉。

我已經嘗試過嘗試背景定位,但是還沒有得到我想要的東西。 有人知道實現此目標的正確方法嗎?

為了澄清,我想實現下面藍色框中所表示的效果(淡出的部分實際上實際上是不可見的):

在此處輸入圖片說明

這是一個相當簡單的解決方案...

HTML

<div class="cat"></div>

CSS

.cat {
    position: absolute;
    background-image: url('http://www.deargrumpycat.com/wp-content/uploads/2013/02/Grumpy-Cat1.jpg');
    background-position: right center;
    background-size: 200px 200px; // set bg size
    height: 200px; // no need for container
    width: 150px;
}

DEMO

您可以通過浮動圖像來完成此操作。

http://jsfiddle.net/9AmVA/2/

#container {
  /* Making crop dimensions bigger so I can see the edge of the cat to know it's working correctly */
  width: 600px;
  height: 500px;
  overflow: hidden;
}

#container:after { clear: right;
    display: block;
    height: 0;
    visibility: hidden;
    content: ' '; }

#container img {
  float: right;
}

這應該工作:

#container {
  width: 150px;
  height: 200px;
  overflow: hidden;
}

#container img {
  width: 200px;
  height: 200px;
  margin-left: -50px;
}
.container {
    max-width: 150px;
    min-width: 150px;
    height: 200px
    display: inline-block;
    background-image: url("PATH-TO/YOUR-IMAGE.JPG");
    background-position: 50% 50%;
    background-repeat: no-repeat;
    background-size: 100%;
    overflow:hidden;
}

.container img {
    display: block;
    position: relative;
    width: 100%;
    height: auto;
    visibility: hidden;
}

通過使用背景大小和位置,您將可以更好地控制圖像的位置或構圖。 您也可以使用javascript自動執行此操作。 我建議不要使用id而是使用className或data屬性。

暫無
暫無

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

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