如何使文本在具有图片背景的 li 元素中水平/垂直居中?
例如:
这是我到目前为止的代码:
#frame {
height: 100%;
}
.frame {
width: 100%;
height: 100%;
padding: 0;
overflow-y: hidden;
}
.frame .slidee {
margin: 0;
padding: 0;
height: 100%;
list-style: none;
}
.frame .slidee li {
float: left;
margin: 0 5px 0 0;
padding: 0;
width: 300px;
height: 98%;
border: solid #CCC 1px;
}
.ad {
background-position: center;
background-size: 100% auto;
}
#ad1 {
background: url("http://blogs.arts.ac.uk/csm/files/2014/03/fashion-revolution.jpg");
}
<div id="frame" class="frame bag_item">
<ul class="slidee">
<li id="ad1"></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
最佳答案
您可以做的最简单的事情就是添加伪元素以帮助垂直对齐:
#ad1:after {
content: '';
display: inline-block;
vertical-align: middle;
height: 100%;
}
为什么会这样?因为文本内容和 :after
伪元素成为同级内联元素,并且由于最后一个元素的高度为 100% 并且具有 vertical-align: middle;
它会自动强制文本也对齐。
查看下面的演示。
/*
Theme Name:
Theme URI:
Description:
Version: 1.0
Author:
Author URI:
*/
html {
color: #444;
font-size: 100%;
background: #f7f7f7 url(../images/bg.png) repeat center top;
height: 100%;
}
body {
line-height: 1;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
height: 100%;
font-size: 62.5%;
color: #000000;
background-color: rgb(240, 240, 240);
color: #777;
font-family: sans-serif;
}
/* Layout container Style */
#main {
padding-top: 6em;
padding-bottom: 3em;
height: 82%;
width: 97%;
padding-left: 1em;
}
#layout, #menu, #frame, .slidee, .menu-link {
-webkit-transition: all 0.3s ease-in-out;
-moz-transition: all 0.3s ease-out;
-ms-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-in-out;
}
.pure-img-responsive {
max-width: 100%;
height: auto;
}
#frame {
height: 100%;
}
.frame {
width: 100%;
height: 100%;
padding: 0;
overflow-y: hidden;
}
.frame .slidee {
margin: 0;
padding: 0;
height: 100%;
list-style: none;
}
.frame .slidee li {
float: left;
margin: 0 5px 0 0;
padding: 0;
width: 300px;
height: 98%;
border: solid #CCC 1px;
}
.ad {
background-position: center;
background-size: 100% auto;
}
#ad1 {
background: url("http://blogs.arts.ac.uk/csm/files/2014/03/fashion-revolution.jpg");
text-align: center;
font-size: 20px;
}
#ad1:after {
content: '';
display: inline-block;
vertical-align: middle;
height: 100%;
}
<div id="frame" class="frame bag_item">
<ul class="slidee">
<li id="ad1" class="ad">
SOME TEXT CONTENT
</li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
关于javascript - 将 li 元素中的文本居中并带有图片背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27764777/