在div中的中心图标 - 水平和垂直 [英] Center icon in a div - horizontally and vertically
问题描述
我有问题将图标集中(垂直和水平)在父div中。我的网页上有许多不同大小的父母 divs
,因此我希望能够按比例将图标放在每个父div的中心。这里有一个JSFiddle的问题:
http:// jsfiddle。 net / kVHbV /
HTML
< div class =img_container>
< i class =icon-play-circle>< / i>
< / div>
< br>
< div class =img_container2>
< i class =icon-play-circle>< / i>
< / div>
CSS
.img_container {
width:100px;
height:100px;
职位:亲属;
背景:红色;
}
.img_container2 {
width:100px;
height:50px;
职位:亲属;
背景:蓝色;
}
.icon-play-circle {
position:absolute;
top:45%;剩余
:45%;
颜色:白色;
c $ c> inline-block 子元素,您可以在父级上设置 text-align:center
,而不必设置 width
或 margin:0px auto
。这意味着它将适用于动态生成的内容,其变化范围 widths
。
。 img_container,.img_container2 {
text-align:center;
这会将 更新: div <
$ b calc()
函数,假定图标的高度已知。
.img_container>我,.img_container2>我{
position:relative;
top:calc(50% - 10px); / * 50% - 图标高度的3/4 * /
}
jsFiddle演示 - 它可以工作。
值得注意的是,您还可以使用 vertical-align:middle
,假设 display:table-cell
是设置在父母身上。
I'm having issues centering icons (both vertically and horizontally) in a parent div. I have many parent divs
on my page that are different sizes, so I want to be able to proportionally place icons in the center of each parent div. Here's a JSFiddle of the problem:
HTML
<div class="img_container">
<i class="icon-play-circle"></i>
</div>
<br>
<div class="img_container2">
<i class="icon-play-circle"></i>
</div>
CSS
.img_container{
width:100px;
height:100px;
position:relative;
background:red;
}
.img_container2{
width:100px;
height:50px;
position:relative;
background:blue;
}
.icon-play-circle{
position:absolute;
top:45%;
left:45%;
color: white;
}
Since they are already inline-block
child elements, you can set text-align:center
on the parent without having to set a width
or margin:0px auto
on the child. Meaning it will work for dynamically generated content with varying widths
.
.img_container, .img_container2 {
text-align: center;
}
This will center the child within both div
containers.
UPDATE:
For vertical centering, you can use the calc()
function assuming the height of the icon is known.
.img_container > i, .img_container2 > i {
position:relative;
top: calc(50% - 10px); /* 50% - 3/4 of icon height */
}
jsFiddle demo - it works.
For what it's worth - you can also use vertical-align:middle
assuming display:table-cell
is set on the parent.
这篇关于在div中的中心图标 - 水平和垂直的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!