我正在尝试创建一个图像呈八边形的设计。我使用了边框黑客,但图像需要在八边形内。在这种情况下,使用伪造元素并不恰当,因为正文也会有自己的背景图像。用css可以吗?
我的代码
div {
width: 100vh;
height: 100vh;
background: gold;
position: relative;
}
div:before {
content: "";
position: absolute;
top: 0;
left: 0;
border-bottom: 29vh solid gold;
border-left: 29vh solid white;
border-right: 29vh solid white;
width: 42vh;
height: 0;
}
div:after {
content: "";
position: absolute;
bottom: 0;
left: 0;
border-top: 29vh solid gold;
border-left: 29vh solid white;
border-right: 29vh solid white;
width: 42vh;
height: 0;
}

<div></div>
&#13;
我希望这张图片位于黄金区域:http://images.visitcanberra.com.au/images/canberra_hero_image.jpg。另外,我使用了vh,以便它对窗口高度做出响应。
答案 0 :(得分:4)
将背景图片放在小提琴中:Fiddle
<div class='octa'></div>
CSS:
将图片用作背景:background-image: url('http://lorempixel.com/400/400/nature');
.octa {
height: 250px;
overflow: hidden;
position: absolute;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
transform: rotate(45deg);
width: 250px;
}
.octa:after {
background-color:#cecece;;
bottom: 0;
content: '';
left: 0;
position: absolute;
right: 0;
top: 0;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
transform: rotate(45deg);
}
.octa {
height: 100vh;
overflow: hidden;
position: absolute;
transform: rotate(45deg);
-webkit-transform: rotate(45deg);
width: 100vh;
}
.octa:after {
background-image: url(http://images.visitcanberra.com.au/images/canberra_hero_image.jpg);
background-position: center center;
background-size: auto 100vh;
bottom: 0;
content: '';
left: 0;
position: absolute;
right: 0;
top: 0;
transform: rotate(-45deg);
-webkit-transform: rotate(-45deg);
}
&#13;
<div class='octa'></div>
&#13;
答案 1 :(得分:0)
你需要做的是在你的形状中制作一个包含图片的div。然后将形状的溢出设置为隐藏,将背景颜色设置为透明,以便只显示形状内部的图像部分。
然后使用此代码将图像的高度和宽度设置为等于包含它的div
.pic img{
width:100%;
height:100%;
}
最终代码看起来像这样
<div>
<div class="pic">
<img src="http://images.visitcanberra.com.au/images/canberra_hero_image.jpg">
</div>
</div>
div {
width: 100vh;
height: 100vh;
background: transparent;
position: relative;
overflow:hidden;
}
.pic{
width:120vh;
height:120vh;
}
.pic img{
width:100%;
height:100%;
}
div:before {
content: "";
position: absolute;
top: 0;
left: 0;
border-bottom: 29vh solid transparent;
border-left: 29vh solid #fff;
border-right: 29vh solid #fff;
width: 42vh;
height: 0;
}
div:after {
content: "";
position: absolute;
bottom: 0;
left: 0;
border-top: 29vh solid transparent;
border-left: 29vh solid #fff;
border-right: 29vh solid #fff;
width: 42vh;
height: 0;
}
在行动here
中查看