2017-02-13 93 views
1

我在嵌套div .box中附上了一个图像。如果它没有浮动,图像可以精确居中到.box,但当我floatleftright中心对齐消失!我有4个不同大小的图像,需要将它们集中在自己的.box中。我该如何解决它?为什么不能在“div”中将图像置于“float”的右侧或左侧?

HTML

<div class="con"> 
    <div class="box"> 
     <img src="../_images/icon-test.png"> 
    </div> 
    </div> 

CSS

.con { 
    width:300px; 
    height:200px; 
    background: #996600; 
} 

.box { 
    position:relative; 
    width:150px; 
    height:150px; 
    background-color: #333333; 
    display:table-cell; 
    text-align:center; 
    vertical-align:middle; 
    float:right; 
} 
+0

你为什么用'如果你想中心元素float'?你要么浮动,要么居中,而不是两者。 – Justinas

+0

@Justinas,我想将图像集中到.box div而不是div元素, – Manoj

回答

1

您可以使用display: flex这一点。

将您的display: table-cell更改为display: flex

然后将text-align:center;vertical-align:middle;改为​​和justify-content: center;,使其垂直和水平居中。

编辑:然后,我还为图像添加了150像素的最大宽度,以在图像大于图像时阻止它从容器中展开。指向@Hkidd指出发生这种情况。

.con { 
 
    width: 300px; 
 
    height: 200px; 
 
    background: #996600; 
 
} 
 
.box { 
 
    position: relative; 
 
    width: 150px; 
 
    height: 150px; 
 
    background-color: #333333; 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: center; 
 
    float: right; 
 
} 
 
img { 
 
    max-width: 150px; 
 
}
<div class="con"> 
 
    <div class="box"> 
 
    <img src="http://placehold.it/200x100"> 
 
    </div> 
 
</div>

+0

那么对于flex语法的浏览器支持如何呢?例如,如果OP必须支持iOS Safari,会发生什么? – Hkidd

+0

@Hkidd在这里看到 - http://caniuse.com/#feat=flexbox –

+0

那么如果图像超出其父级的大小会发生什么? – Hkidd

1

说明

我认为你必须在imgabsolute的位置,所以它会因为.box定位绝对其父.box相对定位。由于img不在表格内,display: table-cell;也是不必要的。

这是我想出了:

.con { 
 
    background: #996600; 
 
    height: 200px; 
 
    width: 300px; 
 
} 
 
.box { 
 
    background-color: #333333; 
 
    float: right; 
 
    height: 150px; 
 
    position: relative; 
 
    width: 150px; 
 
} 
 
.box img { 
 
    bottom: 0; 
 
    left: 0; 
 
    margin: auto; 
 
    position: absolute; 
 
    right: 0; 
 
    top: 0; 
 
    width: 90%; 
 
}
<div class="con"> 
 
    <div class="box center"> 
 
    <img src="http://placehold.it/120x100"> 
 
    </div> 
 
</div>

+1

那么如果OP有不同大小的图像会发生什么? –

+0

@CalvT你是对的,我有4个不同大小的不同图像,放在4个盒子里。 – Manoj

1

如果你有一个形象的问题,你可以使用line-height解决方案,它会将图像准确地在中心.box div &在图像上使用vertical-align: middle。适用于所有浏览器&简单易懂。

参考代码:

.con { 
 
    width: 300px; 
 
    height: 200px; 
 
    background: #996600; 
 
} 
 
.box { 
 
    position: relative; 
 
    width: 150px; 
 
    height: 150px; 
 
    background-color: #333333; 
 
    text-align: center; 
 
    vertical-align: middle; 
 
    float: right; 
 
    line-height: 150px; 
 
} 
 
img { 
 
    height: 60px; 
 
    vertical-align: middle; 
 
}
<div class="con"> 
 
    <div class="box"> 
 
    <img src="http://www.w3schools.com/css/img_fjords.jpg"> 
 
    </div> 
 
</div>

相关问题