我有以下HTML(Fiddle Example):
<header>
<div class="wrapper">
<em class="brand">
<img src="http://via.placeholder.com/200x40?text=LOGO"/>
</em>
<nav class="menu">
<ul class="menu">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</div>
<div class="slides">
<div class="slide">
<div class="frame">
<img src="http://via.placeholder.com/1200x400?text=Image to Crop" />
</div>
<div class="text">
<h2>Our Message</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
</div>
</header>
<main>
Main content
</main>
通讯员CSS:
header {
text-align: center;
}
div.wrapper {
margin: 0 auto;
max-width: 640px;
text-align: left;
position: relative;
}
em.brand img {
display: block;
}
ul.menu {
list-style: none;
margin: 0;
padding: 0;
}
ul.menu li {
display: inline-block;
margin: 0;
padding: 8px;
}
ul.menu li a {
text-decoration: none;
font-size: 18px;
color: white;
}
em {
border: 1px solid red;
position: absolute;
z-index: 2000;
}
nav {
position: absolute;
z-index: 2000;
right: 0;
}
.slides {
width: 100%;
position: relative;
}
.slide .frame img {
width: 100%;
margin: 0 -100px;
}
.slide .text {
position: absolute;
text-align: center;
top: 80px;
width: 100%;
}
.slide .text h2 {
color: white;
font-size: 40px;
margin: 8px;
}
.slide .text p {
color: white;
font-size: 20px;
margin: 8px;
}
main {
border: 1px solid red;
font-size: 20px;
}
使用媒体查询我有时需要通过在左/右或底部/顶部裁剪来调整图像:
.slide .frame img {
width: 100%;
margin: 0 -100px;
}
这不会改变图像。如果我尝试上/下:它只会改变它:
.slide .frame img {
width: 100%;
margin: -100px 0;
}
知道为什么吗?
答案 0 :(得分:1)
您必须设置图像容器的负边距,并设置图像宽度:100%
.slides {
width: 100%;
position: relative;
overflow: hidden; // so the "negative" part is not visible
}
.slide .frame {
margin: 0 -100px;
}
.slide .frame img {
width: 100%;
}
但也许您应该将图片作为背景并使用属性background-size: cover;
和background-position: center;