我有一个居中的div(使用绝对定位和变换:翻译(-50%, - 50%),如here所述)。当子div的内容很短时,一切正常。当内容很长时,子div宽度限制为容器div的50%(可能因为left设置为50%)。
是否有办法允许子div仅在内容很长时才扩展到整个宽度?
for $dept in doc("catalog.xml")/catalog/product/@dept
return <product dept="{$dept}"/>
&#13;
.container {
position: relative;
display: inline-block;
width: 200px;
height: 200px;
margin-left: auto;
margin-right: auto;
border: 2px solid black;
}
.child {
position: absolute;
transform: translate(-50%, -50%);
left:50%;
top:50%;
background:lightgreen;
}
&#13;
修改:我找到了一个解释,帮助我在this回答中解决了这个问题。
答案 0 :(得分:1)
只需在子div中添加display: table
,就可以得到所需的结果。
.container {
position: relative;
display: inline-block;
width: 200px;
height: 200px;
margin-left: auto;
margin-right: auto;
border: 2px solid black;
}
.child {
display: table;
position: relative;
transform: translate(-50%, -50%);
left: 50%;
top: 50%;
background:lightgreen;
}
<div class="container">
<div class="child">short</div>
</div>
<div class="container">
<div class="child">long long long long long long long</div>
</div>
如果你可以使用flexbox
,你也可以这样做:
.container {
display: inline-flex;
align-items: center;
justify-content: center;
vertical-align: top;
width: 200px;
height: 200px;
border: 2px solid black;
}
.child {
background:lightgreen;
}
<div class="container">
<div class="child">short</div>
</div>
<div class="container">
<div class="child">long long long long long long long</div>
</div>
答案 1 :(得分:0)
添加一个额外的嵌套元素,以便您自己更好地控制相关元素的动态定位和缩放。
.container {
position: relative;
display: inline-block;
width: 200px;
height: 200px;
margin-left: auto;
margin-right: auto;
border: 2px solid black;
box-sizing: border-box;
}
.child {
position: absolute;
top: 50%;
left: 0;
right: 0;
text-align: center;
}
.child-inner {
background: lightgreen;
left: 0;
right: 0;
display: inline-block;
}
&#13;
<div class="container">
<div class="child"><div class="child-inner">short</div></div>
</div>
<div class="container">
<div class="child"><div class="child-inner">long long long long long long long</div></div>
</div>
&#13;