[英]css relative position keep inside container
该代码将元素居中,但是如果内容比容器高,则元素顶部的一部分将保留在容器顶部上方。 有没有一种方法可以强制元素保留在容器内? 尽管我敢肯定javascript可以实现,但这可能很难看。 我宁愿一个CSS选项。 只要指出正确的方向即可。
编辑:
我不想“隐藏”溢出,我想相反。 访问jsfiddle将预览面板的尺寸调整为小于元素,您将明白我的意思
HTML
<div class="fill">
<div class="myClass">
hello world!
</div>
</div>
CSS
.fill {
height:100%;
width: 100%;
}
.myClass {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
将其包装在max-height: 100%
和max-width: 100%
的inline-block
容器中,然后对容器进行定位。 将大小和样式应用于容器内的元素
( 演示 )
HTML
<div class="fill">
<div class="wrap">
<div class="myClass">
hello world!
</div>
</div>
</div>
CSS
.wrap {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
max-height: 100%;
max-width: 100%;
display: inline-block;
}
.myClass {
width: 300px;
height: 200px;
}
如果您希望文本垂直居中,请检查此内容。 您的行高过大,这就是为什么它隐藏了其余内容。
html, body { width: 100%; height: 100%; padding: 0; margin: 0; } .fill { width: 100%; height: 100%; } .myClass { position: relative; top: 50%; left: 50%; transform: translate(-50%,-50%); } .myClass { width: 300px; line-height:200px; background: rgb(50,150,250); text-align: center; color: #fff; font-weight: bold; font-family: sans; font-size: 2rem; border-radius: 2px; display: -ms-flexbox!important; display: -webkit-flex!important; display: flex!important; -ms-flex-align: center; -webkit-align-items: center; -webkit-box-align: center; align-items: center; line-height: normal; padding-top: 15px; padding-bottom: 15px; max-height: 100%; }
<div class="fill"> <div class="myClass"> hello world! Long text here! Blah Blah blah! Chewie! </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.