如何将图像对齐在响应容器的顶部?

时间:2016-06-06 18:13:29

标签: html css css3 responsive

我正在尝试连续排列两个响应式容器。其中一个图像内部设置为宽度:100%和高度:自动。如何垂直对齐其父响应容器顶部的图像?

<div class="top-row">
  <figure class="product-image col-sm-6">
    <img src="http://rastenis.lt/coocoo/image/cache/catalog/Demo/Untitled.Oil%20on%20canvas.45x55%20cm.2011-570x600.JPG" class="img-r" alt="img">
  </figure>
  <article class="description col-sm-6">
    <h1 class="p-heading">ELEPHANTS ARE COMING BACK</h1>
    <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes </p>
  </article>
</div>

CSS

.top-row {
  width: 100%;
}
figure img {
  width: 100%;
  height: auto;
}

以下是我的示例:https://jsfiddle.net/2sg209o0/

3 个答案:

答案 0 :(得分:0)

我不太确定你想做什么。您是否帮助对齐行中的div或将图像垂直对齐在自己的行中?如果是后者,则要使用vertical-align(http://www.w3schools.com/cssref/pr_pos_vertical-align.asp)。

答案 1 :(得分:0)

您的图片存在问题。更改图像链接并再次检查。您的图像包含顶部白色区域,逻辑上您的图像位于父容器的顶部。最好的选择是剪裁我认为的图像。

答案 2 :(得分:0)

此处显示的示例代码:https://jsfiddle.net/2sg209o0/包含您正在寻找的正确代码的 。要验证这一点,请随意将此CSS添加到适当的选择器中,以便您的CSS看起来像这样:

.top-row {
    width: 100%;
    border:1px dotted blue;
}
figure img {
    width: 100%;
    height: auto;
    border:1px dashed red;
}

如果要右键单击图像并检查元素,您将看到图像顶部和底部包含白色像素。正如您所问,图像确实沿着直接容器的顶部边缘对齐:

  

如何垂直对齐其父响应容器顶部的图像?

但是,您似乎要求图像在包含div的顶部对齐,&#34; top-row&#34;以及其他内容。为此,您需要添加更多样式。也就是说,问题围绕浮动和你使用的&#34;图&#34;元件。

与其他许多标签一样,数字标签从浏览器中获得预先存在的样式。其中一种风格是保证金。阅读下面的代码块后,随意点击以下JS小提琴链接,查看实例中的最终代码。我已经添加了必要的样式并为您裁剪图像(并将其置于imgur上)。您可以根据自己的出价进行自定义;我不完全确定最终目标是什么,除了某种形式的产品展示。

.top-row {
  width: 100%;
  border:1px dotted red; /* to show you top-row's boundaries */
}

figure{
  margin:0 1em 1em 0; /* override browser styles */
  width:50%;   /* give article some room in top-row */
  float:left;  /* floats are powerful tools for layouts and whatnot */
}

figure img {
  width: 100%;
  height: auto;
}

https://jsfiddle.net/pa04oxmt/

注意:您的图片可能会溢出其容器,但我确定您知道如何解决该问题:)编辑:修复错字n whatnot