css相对位置保持在容器内 [英] css relative position keep inside container
问题描述
此代码使元素居中,但如果内容高于容器,则元素顶部的一部分将位于容器顶部之上。是否有一种强制元素留在容器中的方法?虽然我相信这是可能与javascript,它可能会很丑陋。我宁愿一个css选项。
This code centers an element, but if the content is taller than the container a portion of the top of the element will be left above the top of the container. Is there a method of forcing the element to stay within the container? Though I'm sure it's possible with javascript, it would probably be pretty ugly. I would rather a css option. Just point me in the right direction.
我不想隐藏溢出,只是指向正确的方向。
,我想要相反。访问jsfiddle调整比元素小的预览面板,你会看到我的意思
I do not want to "hide" the overflow, I want the opposite. Visit the jsfiddle resize the preview panel smaller than the element and you will see what I mean
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%);
}
推荐答案
c $ c> max-height:100%和 max-width:100% code>然后应用定位到容器。将大小和样式应用于容器内的元素
Wrap it in an inline-block
container with max-height: 100%
and max-width: 100%
then apply positioning to the container. Apply sizing and styling to the element inside the container
(示范)
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;
}
这篇关于css相对位置保持在容器内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!