我有以下代码:JSFiddle。标题是一个粘性元素,一切正常。但是,我想使标题和图标居中,因此我添加了一个包装div:JSFiddle。这里的问题是标题现在粘在包装div而不是content
div上。如何在使标题和图标居中的同时确保定位有效?
这是第二个JSFiddle中的代码:
HTML:
<div class="content">
<div class="menu-wrapper">
<div class="menu">
<p class="menu-title">Title</p>
</div>
<img src="https://apixel.me/static/apixel.png" class="icon" />
</div>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
</div>
CSS:
.menu-wrapper {
display: inline-block;
border: thin red solid;
margin-left: 50%;
transform: translate(-50%, 0);
}
.menu {
position: sticky;
display: inline-block;
width: 150px;
top: 15px;
background-color: #000000c7;
border-radius: 10px;
padding-top: 14px;
padding-bottom: 14px;
padding-left: 25px;
padding-right: 25px;
margin-bottom: 10px;
}
.menu-title {
color: white;
font-family: "Roboto";
font-size: 18px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
margin: 0px;
margin-left: 15px;
}
.icon {
display: inline-block;
width: 50px;
height: auto;
margin-left: 50px;
}
编辑:我只希望标题是粘性的,而不是图标
您可以使用常规文本对齐方式来居中。像这样:
.content {
text-align:center;
}
.content > * {
text-align:left;
}
.menu {
position: sticky;
display: inline-block;
width: 150px;
top: 15px;
background-color: #000000c7;
border-radius: 10px;
padding-top: 14px;
padding-bottom: 14px;
padding-left: 25px;
padding-right: 25px;
margin-bottom: 10px;
}
.menu-title {
color: white;
font-family: "Roboto";
font-size: 18px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
margin: 0px;
margin-left: 15px;
}
.icon {
display: inline-block;
width: 50px;
height: auto;
margin-left: 50px;
}
<div class="content">
<div class="menu">
<p class="menu-title">Title</p>
</div>
<img src="https://apixel.me/static/apixel.png" class="icon" />
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
<p>Filler text</p>
</div>
使包装器具有粘性,而不是标题。
.menu-wrapper {
display: inline-block;
border: thin red solid;
margin-left: 50%;
transform: translate(-50%, 0);
position: sticky;
top: 15px;
}