【问题标题】:<p> element inheriting width from a centered <img> above it<p> 元素从其上方居中的 <img> 继承宽度
【发布时间】:2014-02-19 05:45:41
【问题描述】:

假设我有一个可以是可变宽度的图像(最小:100px,最大:100% [760px])。我还有一个&lt;p&gt; 元素,将显示在图像的正下方。我希望&lt;p&gt; 的宽度与&lt;img&gt; 相同,但我似乎找不到答案。

这是jsfiddle这种场景所涉及的代码:

html

<div id='page'>
    <figure>
        <img src='http://www.myimage.com/img.jpg'/>
        <p>Hi there. I am some text. I would like to start where the image starts :(</p>
    </figure>
</div>

css

#page {
    width:760px; /* arbitrary */
}

figure img {
    display: block;
    border: 1px solid #333;
    max-width: 100%;
    min-width: 100px;
    margin: 0 auto;
}

figure p {
    /* ??? */
}

有什么想法吗?

【问题讨论】:

  • 你喜欢这个jsfiddle.net/a9rEh/1??
  • 您需要为figure 定义一个宽度,即图像的宽度。
  • @davidpauljunior 如果我不知道图像的宽度怎么办?你是说我必须使用 javascript 来读取图像大小,然后根据它改变 css?
  • @Beginner 不幸的是,没有。正如我所提到的,文本将直接显示在图像下方。
  • 你这样做的目的是什么?您要制作字幕吗?

标签: html css


【解决方案1】:

这是我使用的FIDDLE

HTML:

<div id='page'>
    <figure>
        <img src='http://www.iiacanadanationalconference.com/wp-content/uploads/2013/01/test.jpg'/>
        <figcaption>Hi there. I am some text. I would like to start where the image starts :(</figcaption>
    </figure>
</div>

CSS:

#page {
    width:760px; /* arbitrary */
}


figure{
    padding-left: 10%;
}

实际上有几种方法可以制作图片标题,例如使用&lt;table&gt;。我并不是说这是最好的方法。但这是最简单的方法,因为我看到您在那里使用&lt;figure&gt;。希望对您有所帮助。

【讨论】:

  • 我已经减小了图像大小并更新了小提琴。请注意它打破了这个用例
【解决方案2】:

它继承自#page div。不是来自图像。请查看相同的小提琴更新。 但是,您可以控制单个元素。您必须指定您希望它的外观。

【讨论】:

  • 我认为 OP 的意思是他们希望 &lt;p&gt; 继承图像的宽度,而不是它已经是。
  • 哦k,这种情况下他得提前知道图片的宽度。在css中动态设置值??从兄弟姐妹那里继承规则?我不认为这是可能的。
【解决方案3】:

您可以在figure 上使用display: table 并在其上设置小宽度。因为它是一个表格布局,所以它会变得和内容一样宽,在本例中是图像。

figure {
  display: table;
  width: 1%;
}

Demo

【讨论】:

  • 不幸的是,图像不再位于其父元素的中心。
  • 嗯,这是一个有趣的解决方案。你会说这种类型的解决方案会遵循“最佳实践”吗?
  • @a.real.human.being 嗯,这是我所知道的唯一一种仅使用 CSS 的方式,并且在语义上它是正确的。
猜你喜欢
  • 2014-10-28
  • 1970-01-01
  • 1970-01-01
  • 2011-09-29
  • 2019-03-16
  • 2013-12-11
  • 1970-01-01
  • 2014-06-07
  • 2015-10-15
相关资源
最近更新 更多