使用内容大于容器的flexbox时出现问题

时间:2013-07-21 14:46:19

标签: css3 flexbox

我正在尝试使用以下条件将元素(水平和垂直)居中: 元素的显示是内联块,因为我希望根据其内容计算其宽度/高度。

当容器大于元素everything is fine时。

但是,当元素大于容器时,问题开始,the element gets the width of the container and not its content

提前致谢, 奥伦

以防jsFiddle失败,这是代码片段:

<div class="working_area">
    <div class="image_container">
        <img src="http://eofdreams.com/data_images/dreams/bear/bear-05.jpg"/>
    </div>
</div>

.working_area {
  background: yellow;
  position: absolute;  
  width: 600px;
  height: 600px;
  display: -webkit-flex;
  -webkit-justify-content: center;
  -webkit-align-items: center;
}

.image_container {
  display: inline-block; 
    /*shrink a bit*/
    -webkit-transform: scale(0.7);
    /*-webkit-transform-origin: center center;*/
}

3 个答案:

答案 0 :(得分:2)

您是否尝试添加:

.image_container img {
    max-width: 100%;
}

使<img>最大值达到父级的100%,否则只会达到它的全宽并且不会更宽。

<强> fiddle

答案 1 :(得分:1)

将图像的百分比设置为大于容器,并根据图像大小设置负边距。

示例:

.image_container {
    margin:0 -10%;
    width:120%;
}

这是我在你的代码上做的一个例子

http://jsfiddle.net/GPhzq/3/

答案 2 :(得分:1)

使用Flexbox的解决方案:

<强> FIDDLE

(小提琴中包含的浏览器细节)

.working_area{
    background: yellow;  
    width: 600px;
    height: 600px;
    text-align:center;
    display: flex;
    justify-content: center;
    align-items: center;
}

.image_container {
  display: inline-block;  
}

img
{
    max-width: 600px; /* limit img to container width */
}

跨浏览器解决方案:

所有现代浏览器(如IE9)都不支持Flexbox,因此以下解决方案可能是首选方式:

要使图像水平居中:将text-align:center;添加到父容器

垂直中心:由于work_area具有固定的高度,因此可以很容易地实现。只需添加line-height: 600px;到.image_container类和vertical-align:middle;到你的图像类。

<强> FIDDLE

所以你得到:

标记

<div class="working_area">
    <div class="image_container">
        <img src="http://eofdreams.com/data_images/dreams/bear/bear-05.jpg"/>
    </div>
</div>

CSS

.working_area {
  background: yellow;  
  width: 600px;
  height: 600px;
  text-align:center;
    margin-bottom: 20px;
}

.image_container {
  display: inline-block;
  line-height: 600px;  
}
img
{
    max-width: 600px; /* limit img to container width */
    vertical-align:middle;
}
相关问题