Html 将图像垂直居中并向右放置在div中
我想将ID为“image”的图像居中放置在右侧和垂直位置 我使用PHP创建div,如下所示:Html 将图像垂直居中并向右放置在div中,html,css,Html,Css,我想将ID为“image”的图像居中放置在右侧和垂直位置 我使用PHP创建div,如下所示: echo "<div class=\"first\"> <div id=\"second\"><label id=\"second_div_label\"></label> <img id=\"image\" src=\"images/my_image.png\"/> </div> <
echo
"<div class=\"first\">
<div id=\"second\"><label id=\"second_div_label\"></label>
<img id=\"image\" src=\"images/my_image.png\"/>
</div>
<div id=\"third\"></div>
</div>";
多亏了
float:right
图像位于DIV的右侧,但它没有垂直居中,并且边距底部
不起作用。如何解决这个问题?您可以使用position:absolute
技巧,然后使用Sebastian Ekström将其设置为右侧和垂直中心。
请注意,要使其工作,父标记必须具有位置:relative
由于元素是绝对定位的,因此不需要float:right
例如:
。首先{
显示:块;
宽度:50%;
高度:自动;
保证金:0px自动;
边缘底部:15px;
}
#第二{
利润率最高:5%;
背景色:#3f51b5;
边界半径:5px;
字体大小:粗体;
填充:20px;
位置:相对位置;
}
#第三{
边缘顶部:15px;
边界半径:5px;
填充:20px;
}
#形象{
宽度:35px;
高度:35px;
位置:绝对位置;
最高:50%;
右:10px;
转化:translateY(-50%);
}
Aziz的CSS应该可以在现代浏览器中使用。 但是,对于不费吹灰之力的跨浏览器体验,如果你不介意使用JavaScript,你可以考虑使用jQuery,比如:
<script>
$(document).ready(function(){
$('#image').position({
my: 'right center',
at: 'right center',
of: '.first' //or whichever container you wish to use
});
});
</script>
$(文档).ready(函数(){
$(“#图像”)。位置({
我的‘右中’,
在‘右中’,
of:'.first'//或您希望使用的任何容器
});
});
这样,您就不需要在CSS中实现浮动以及相对和绝对定位
#image {
width:35px;
height:35px;
float:right;
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
请将此样式添加到图片中。请注意,还有一件事,您必须定义父div的高度(id=second),并且它的值大于图像高度。这是一个有趣的解决方案,因为它会创建javascript依赖项,并且不适用于禁用javascript的用户
#image {
width:35px;
height:35px;
float:right;
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}