如何在可变宽度的较小div中水平居中可变宽度的较大div [英] How to horizontally center a larger div of variable width, within a smaller div of variable width
本文介绍了如何在可变宽度的较小div中水平居中可变宽度的较大div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想达到以下效果:)。
查看此示例: http://jsfiddle.net / 2SQ4S / 1 /
I want to achieve the following effect: http://jsfiddle.net/3KJta/1/
However the solution I have uses a known width for the small div and the larger div. I need this to work with variable sized divs. The use case for this is a tooltip that appears above a smaller flexible sized element. The tooltip content isn't known and so the width could be anything.
So far I have:
<div class="small">
<div class="smaller"></div>
<div class="larger"></div>
</div>
and
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
div {
border: 2px solid black;
}
.small {
width: 50px;
height: 50px;
position: absolute;
left: 200px;
top: 50px;
text-align: center;
}
.smaller {
width: 20px;
height: 20px;
border-color: red;
display: inline-block;
}
.larger {
width: 200px;
height: 200px;
border-color: blue;
display: inline-block;
margin-left: -75px /* NOTE: in reality, .small has a variable width, and so does .larger, so i can't just take off this fixed margin */
}
解决方案
If you are ok with using css3 and only support modern browsers you can use transform: translateX(-50%);
to center the bigger box (currently supported browsers).
See this example: http://jsfiddle.net/2SQ4S/1/
这篇关于如何在可变宽度的较小div中水平居中可变宽度的较大div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文