使用绝对定位时无法使最大宽度工作 [英] Can't make max-width work when using absolute positioning
问题描述
使用绝对定位时,我无法获得最大宽度
正常工作。在 https://jsfiddle.net/jn2bs6ax/ 中,该项目的宽度应尽可能小,最大最大宽度为1000像素。但是它需要大约50%的宽度并包裹文字。如何使其运作?如果我将max-width设置为300px之类的值,那么它可以工作,但是任何大于当前宽度的值都不会导致其扩展。
I can't get max-width
to work when using absolute positioning. In https://jsfiddle.net/jn2bs6ax/ the item should take as little width as possible, up to the max-width of 1000px. But it's taking a width of about 50% and wrapping the text. How to make it work? If I set the max-width to something small like 300px it works, but anything larger than what it's width currently is doesn't cause it to expand.
此示例仅显示了一个绝对位于下方项目中心的项目,但是我使用了 transform
, top
,底部
,左左
和右
定位相对于一个项目在所有四个方向上的事物。该解决方案应适用于所有4种情况。
This example just shows an item that's been absolutely positioned to the center below an item, but I use transform
, top
, bottom
, left
and right
to position things in all 4 directions relative to an item. The solution should work with all 4 cases.
有一个类似的问题 CSS(位置:绝对+左侧:50%=最大宽度:50%)?,但答案仅适用于下方居中的情况,但不适用于所有情况,例如垂直放置在项目右侧
There's a similar question CSS (position:absolute + left:50% = max-width:50%)? but the answer only works with centering below but not for all cases like positioning to right of an item vertically centered.
<div class="relative">
text
<div class="absolute">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim recusandae doloribus nesciunt unde vitae quis aliquid laborum adipisci ipsa, dolorem repellendus nulla iure atque minus fuga sunt rem eaque animi.</div>
text
</div>
css
.relative {
position: relative;
}
.absolute {
position: absolute;
background-color: grey;
max-width: 100%;
top: 100%;
left: 50%;
transform: translateX(-50%);
}
推荐答案
您已经注意到,问题与 left:50%
有关,它将元素的宽度限制为父元素的 50%
。
As you already noticed, the issue is related to left:50%
that will restrict the width of the element to 50%
of the parent element.
一种克服此问题的方法是通过添加更多的填充来增加父元素的宽度,因为绝对元素会考虑填充框。然后,添加负边距以纠正添加的填充。您只需要注意溢出:
One hacky way to overcome this is to increase the width of the parent element by adding more padding since absolute element will consider the padding-box. Then you add negative margin to rectify the added padding. You should simply pay attention to overflow:
.relative {
position: relative;
padding:0 50%;
margin:0 -50%;
}
.absolute {
position: absolute;
background-color: grey;
max-width: 800px;
top: 100%;
left: 50%;
transform: translateX(-50%);
}
.hide {
overflow:hidden;
height:500px;
}
<div class="hide">
<div class="relative">
text
<div class="absolute">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim recusandae doloribus nesciunt unde vitae quis aliquid laborum adipisci ipsa, dolorem repellendus nulla iure atque minus fuga sunt rem eaque animi.</div>
text
<div class="absolute" style="top:200px;">Lorem ipsum dolor sit amet</div>
</div>
</div>
这篇关于使用绝对定位时无法使最大宽度工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!