简体   繁体   English

仅当子级宽度不为100%时,才向容器中添加填充

[英]Add padding to container only when children is not 100% width CSS

So I have a couple container holding that have an image and I'm trying to add padding to the container only if the images is less than the width of the container. 因此,我有几个容器容器,其中有一个图像,并且仅在图像小于容器宽度的情况下,才尝试向容器中添加填充。 I know this will be a simple javascript solution but is there a way to do this with css? 我知道这将是一个简单的javascript解决方案,但是有没有办法用CSS做到这一点?

Example html: 范例html:

<div class="image-container">
  <img scr="my/path/to/image"/>
</div>
<div class="image-container">
  <img scr="my/path/to/image2"/>
</div>

css: I dunno :) CSS:我不知道:)

Take a look at this image to get a better idea of what I'm trying to do: http://grab.by/r1sS 看一下这张图片,以更好地了解我要做什么: http : //grab.by/r1sS

It is not possible to add padding based on the image size using CSS. 无法使用CSS根据图像大小添加填充。

Although, From the link you provided it looks like you are trying to center the image. 虽然,从您提供的链接看来,您正试图将图像居中。 You can achieve this by setting text-align to center on the container which will center the child elements ie. 您可以通过将text-align设置为在容器上居中以将子元素居中,即居中来实现此目的。 the image. 图片。

.image-container {
    text-align: center;
}

In regards to the original query, it is not possible to add padding based on the image size using CSS. 对于原始查询,无法使用CSS根据图像大小添加填充。

I'm not aware of any way to apply the exact conditional you're asking for in pure CSS since CSS has no conditionals. 我不知道有什么方法可以在纯CSS中应用您要的确切条件,因为CSS没有条件。

But, based on your screen shot it seems like you don't need padding. 但是,根据您的屏幕快照,似乎不需要填充。 Why not just center the image over a colored background. 为什么不将图像居中放置在彩色背景上呢? Won't that accomplish the same thing? 那不会完成同一件事吗?

When the image is full width, it will cover the entire background and fill the container. 当图像为全角时,它将覆盖整个背景并填充容器。 When it's not full width, it will be centered in the container. 如果不是全角,它将在容器中居中。

To center the image in the container and apply a background color: 要将图像居中放置在容器中并应用背景色:

.image-container {
    text-align: center;
    background-color: #777;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM