CSS:如何将容器大小设置为等于背景图像大小 [英] CSS: How to set container size equal to background image size

查看:219
本文介绍了CSS:如何将容器大小设置为等于背景图像大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何拉伸背景图像以适合其容器(具有background-size属性).但是,如何在不手动设置宽度和高度的情况下实现另一种解决方法呢?

I know how to stretch background image to fit its container (with background-size property). But how to achieve the other way around without setting width and height manually?

为更好地说明我的观点,假设我们有一个p元素,其中包含一行文本,并将其背景图像设置为800 * 600px的图片.如何自动将p 的宽度和高度调整为800 * 600?

To better make my point, assume we have a p element with one line of text and set its background-image to an picture of 800*600px. How to adjust the width and height of p automatically to 800*600?

我问这个问题是因为我正在寻找更好的工作流程.每当我在Photoshop中更改图像大小时,更改CSS中的宽度和高度都是很烦人的.工作流程如下:

I ask the question because I am looking for a better workflow. It's quite annoying to change width and height in CSS every time I change the image size in Photoshop. The workflow is like below:

  1. 在Photoshop中更改图像(最终可能会得到稍微不同的图像尺寸)
  2. 记住新的维度
  3. 进入CSS文件,查找使用该图像作为bg的特定元素
  4. 更改元素的宽度和高度(如果我仍然没记错的话..)

推荐答案

可以使用img元素并将包含div的显示设置为inline-block,而不是使用背景图片.然后,您需要创建一个内部div来包装内容并将其相对于所包含的div绝对定位.由于img是流中唯一的内容,因此包含div的大小将相对于图像进行调整.

Instead of using a background image, you could use a img element and set the containing div's display to inline-block. You'd then need to create an inner div to wrap the content and position it absolutely relative to the containing div. Since the img is the only thing in the flow, the containing div will resize relative to the image.

几乎是个hack,但我认为它会产生您想要的效果.

Pretty much a hack, but I think it would give the effect you are looking for.

http://jsfiddle.net/Km3Fc/

HTML

<div class="wrap">
    <img src="yourImg.jpg" />
    <div class="content">
        <!-- Your content here -->
    </div>
</div>

CSS

.wrap {
    display: inline-block;
    position: relative;
}

.wrap img + .content {
    position: absolute;
    top: 0;
    left: 0;
}

这篇关于CSS:如何将容器大小设置为等于背景图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆