我有一个宽度为 180px
,高度为 180px
的 div
。
如何在容器内水平垂直居中一个 FontAwesome 图标?
注意:我可能会在图标下面添加文本。
<div style="width:180px; height:180px; float:left;">
<i class="fa fa-search fa-4x"></i>
</div>
应该长成这个样子:
我有一个宽度为 180px
,高度为 180px
的 div
。
如何在容器内水平垂直居中一个 FontAwesome 图标?
注意:我可能会在图标下面添加文本。
<div style="width:180px; height:180px; float:left;">
<i class="fa fa-search fa-4x"></i>
</div>
试试这个:
.centered{
position:relative;
top:50%;
left:50%;
transform:translate(-50%,-50%)
}
.container{
width:100px;
height:100px;
}
#search{
background: gray;
width:180px;
height:180px;
float:left;
line-height: 180px;
text-align: center;
vertical-align: bottom;
}
#search > p {
margin-top: -155px;
}
示例工作 http://jsfiddle.net/kasperFranz/h91p8w4e/3/ (在示例中使用图标而不是fa,但不应影响结果。)
我可能来晚了,但这是一个常见的问题,所以这里有一个简单可行的想法,它有趣的一面在于它可以适应容器大小:
span{
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
position: absolute;
text-align: center;
width: 15px;
height: 15px;
display: block;
}
<div class="myDiv">
<div class="content_wrapper">
<!--i class="fa fa-search fa-4x">test</i-->
<i class="icon-search icon-4x"></i><br />
<span class="myText">Search</span>
</div>
</div>
css
.myDiv{
width: 180px;
height: 180px;
float: left;
background: #ccc;
text-align: center;
display: table;
}
.content_wrapper{
display: table-cell;
vertical-align: middle;
}
.myText{
font-weight: bold;
font-size: 20px;
}
/* This parent can be any width and height */
.block {
text-align: center;
background:#ccc;
margin-bottom:10px;
}
/* The ghost, nudged to maintain perfect centering */
.block:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
/* The element to be centered, can
also be of any width and height */
.centered {
display: inline-block;
vertical-align: middle;
width: 300px;
}
<div class="block" style="height: 300px;">
<div class="centered">
<h1>Some text</h1>
<p>p1</p>
</div>
</div>
<div class="block" style="height: 200px;">
<div class="centered">
<h1>Some text</h1>
<p>p2</p>
</div>
</div>
<div class="block" style="height: 600px;">
<div class="centered">
<h1>Some text</h1>
<p>p3</p>
</div>
</div>
更新 1: 演示
;)
不确定他想做什么。我的回答是正确的。谢谢你的好奇心。**:))** - Hamix简单的方法是将 display: grid; place-items: center;
添加到你的 div 标签里,然后你就可以开始了。
像这样:
<div style="width:180px; height:180px; display: grid; place-items: center;">
<i class="las la-user-circle"></i>
</div>
我知道可能有点晚了,你可能已经解决了这个问题。
我通过将图标和文本包装在一个 div 中,然后对其添加填充来实现你想要的效果。
请查看附带的代码片段。
http://codepen.io/ForTheJim/pen/YPxveR
<p data-height="268" data-theme-id="0" data-slug-hash="YPxveR" data-default-tab="result" data-user="ForTheJim" class='codepen'>See the Pen <a href='http://codepen.io/ForTheJim/pen/YPxveR/'>Centering Icon Question</a> by Jim (<a href='http://codepen.io/ForTheJim'>@ForTheJim</a>) on <a href='http://codepen.io'>CodePen</a>.</p>
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>