如何使:: after元素具有与其前一个兄弟相同的宽度

时间:2018-01-19 22:35:28

标签: html css

我有一个<div>容器,其中包含<img>::after伪元素。像这样:

<div class="container" data-caption="this caption should be as wide as the image and then wrap">
  <img>
</div>
.container {
  display: inline-block
}
.container::after {
  display:      block
  background:   #aabbaa
  content:      attr(data-caption)
  line-height:  40px
  padding:      0 1rem
}    

容器应该从包含的图像中获取其宽度,而::after元素应相应地包装其内容,如下所示:

enter image description here

相反,after元素不会换行 - 请参阅this codepen

enter image description here

2 个答案:

答案 0 :(得分:1)

编辑动态继承图片而非文字<?php $row = [ 'address' => '1315 10th St.', 'city' => 'Sacramento', 'state' => 'CA', 'zip' => '95814' ]; $address = str_replace(' ', '+', $row['address'] ) . ',' . str_replace(' ', '+', $row['city'] ) . ',' . str_replace(' ', '+', $row['state'] ) . ',' . str_replace(' ', '+', $row['zip'] ); function get_gps_coordinates_of_street_address( $address ) { $url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $address; if( $response = @file_get_contents( $url ) ) { $geo = json_decode( $response, TRUE ); if( $geo['status'] == 'OK' ) { return $geo['results'][0]['geometry']['location']['lat'] . ',' . $arr['results'][0]['geometry']['location']['lng']; } else { return 'GPS coordinates were not available for supplied ADDRESS'; } } else { return 'GPS coordinates were not available because connection failed or malformed request'; } } var_dump( get_gps_coordinates_of_street_address( $address ) );

use max-width: min-content

答案 1 :(得分:1)

您可以使用一些定位黑客,使用相对父级和绝对伪元素。看这里: https://codepen.io/palash/pen/dJabRr

此外,white-space: wrap doesn't exist,您正在寻找white-space: normal,这是默认值。 (nowrap确实存在。)

.container
  position: relative
  ...
  &::after
    ...
    position:     absolute
    left:         0
    right:        0

编辑:如果您不想使用绝对定位(因此边框也会出现在标题周围),您可以使用flexbox来执行此操作 -

更新了笔:https://codepen.io/palash/pen/BYyXjq

.container
  display: flex
  flex-direction: column
  align-items: flex-start
  width: min-content
  ...
  &::after
    background:   #aabbaa
    content:      attr(data-caption)
    line-height:  40px
    padding:      0 1rem