我有一个包含数据内容的div,用于悬停效果。它看起来像这样:
HTML:
<div data-content="TEXT THAT NEEDS TO BE POSITIONED" class="teamleft">
</div>
感谢stackoverflow,我发现整齐的css代码使用:after和:hover:after可以使悬停效果成为可能。我唯一无法弄清楚的是定位和设计数据内容文本。我想垂直居中我的文字。另外,如何在一个数据内容中添加不同样式的文本?或者我可能应该使用两种不同的数据内容?
CSS:
teamleft
{
position: absolute;
width:50%;
height: 100%;
background-color: #25335a;
}
.teamleft:after
{
position: absolute;
width: 100%;
height: 100%;
content: attr(data-content);
color:#fff;
background:rgba(0,0,0,0.6);
opacity:0;
transition: all 0.5s;
-webkit-transition: all 0.5s;
}
.teamleft:hover:after
{
opacity:1;
}
提前致谢!
JSFiddle:https://jsfiddle.net/e8t2gcxg/3/
答案 0 :(得分:1)
试试这段代码:
.teamLeft:after {
position: absolute;
width: 100%;
height: 20px;
top:calc(50% - 10px);
content: attr(data-content);
text-align:center;
color:#fff;
background:rgba(0,0,0,0.6);
opacity:0;
transition: all 0.5s;
-webkit-transition: all 0.5s;
}
将:after
的高度更改为20px;
,然后使用顶部并将其更改为父div高度50%
的{{1}}({{1}的高度的一半})。应用-10px
水平居中文本。
修改强>
查看此链接;它应该有所帮助。
答案 1 :(得分:0)
使用包装器div。
.teamleft
{
position: absolute;
width:300px;
height: 30px;
background-color: #25335a;
}
.teamleft:after
{
position:absolute;
width: 300px;
height: 30px;
content: attr(data-content);
color:#fff;
background:rgba(0,0,0,0.6);
opacity:0;
transition: all 0.5s;
-webkit-transition: all 0.5s;
}
.teamleft:hover:after
{
opacity:1;
}
#wrapper{background-color: #25335a;
width:400px;
height:200px;}
p{margin-left:50px;
top:calc(50% - 10px);
}
&#13;
<div id="wrapper">
<p data-content="TEXT THAT NEEDS TO BE POSITIONED" class="teamleft">
</p>
</div>
&#13;
答案 2 :(得分:0)
通过将.teamleft
与另一个块元素包装为flex-container(.flexShell
)并将另一个类(.flexItem
)添加到.teamleft
,我将内容纵向和横向居中}。 .flexItem
属性允许它在其新的父.flexShell
中居中。
<main class="flexShell">
<div data-content="TEXT THAT IS POSITIONED DEAD CENTER! THIS ADDED TEXT IS TO TEST THE WIDTH AND WRAPPING CAPABILITIES" class="teamleft flexItem">
</div>
</main>
评论中提供了对所用样式属性的引用。
/*=-=-[ RESET PROPERTIES ]-=-=*/
/* http://goo.gl/3ed2H */
html {
box-sizing: border-box;
font: 500 16px/1.5 Consolas;
}
*, *:before, *:after {
box-sizing: inherit;
margin: 0;
padding: 0;
border: 0;
}
/*=-=-[ FLEXBOX CLASSES ]-=-=*/
/* https://goo.gl/WySM2z */
.flexShell {
display: flex;
display: -webkit-flex;
position: relative;
overflow-y: none;
}
.flexItem {
flex: 1 0 auto;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
overflow-y: none;
}
/*=-=-[ TEAMLEFT ]-=-=*/
.teamleft {
position: absolute;
width: 50vw; /* http://goo.gl/DkXR5F */
height: 100vh;
background-color: #25335a;
}
.teamleft:after {
position: absolute;
left: 25%; /* https://goo.gl/S1mNoN */
top: 50%;
content: attr(data-content);
color: #fff;
background: rgba(0, 0, 0, 0.6);
opacity: 0;
transition: all 0.5s;
-webkit-transition: all 0.5s;
text-align: center;
width: 50%;
background-color: transparent;
display: table-cell; /* https://goo.gl/lzmCyg */
overflow-y: none; /* https://goo.gl/o1Oqbf */
}
.teamleft:hover:after {
opacity: 1;
}