[英]Center image vertically and to the right in a div
我想将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>
<div id=\"third\"></div>
</div>";
我的CSS代码是
.first {
display: block;
width: 50%;
height: auto;
margin: 0px auto;
margin-bottom: 15px;
}
#second {
margin-top: 5%;
background-color: #3f51b5;
border-radius: 5px;
font-weight: bold;
padding: 20px;
}
#third {
margin-top: 15px;
border-radius: 5px;
padding: 20px;
}
#image {
width: 35px;
height: 35px;
float: right;
}
多亏了float:right
,图片位于DIV的右侧,但它不是垂直居中,并且页margin-bottom
不起作用。 我该如何解决?
您可以使用position:absolute
技巧,然后使用SebastianEkström的出色代码将其设置在右侧并垂直居中。 请注意,要使其正常工作,父标记必须具有position:relative
由于该元素是绝对定位的,因此不需要float:right
例:
.first { display: block; width: 50%; height: auto; margin: 0px auto; margin-bottom: 15px; } #second { margin-top: 5%; background-color: #3f51b5; border-radius: 5px; font-weight: bold; padding: 20px; position:relative; } #third { margin-top: 15px; border-radius: 5px; padding: 20px; } #image { width: 35px; height: 35px; position:absolute; top: 50%; right:10px; transform: translateY(-50%); }
<div class="first"> <div id="second"> <label id="second_div_label"></label> <img id="image" src="http://i.stack.imgur.com/CE5lz.png"/> </div> <div id="third"></div> </div>
PS,您可能要为transform属性添加供应商前缀
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: 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>
然后,您将不需要在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)的高度,并且其值大于图像高度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.