将宽度未知的HTML元素居中到屏幕中间 [英] Center an HTML element with an unknown width to the middle of the screen
本文介绍了将宽度未知的HTML元素居中到屏幕中间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我的HTML元素的宽度和高度未知,如何将其居中放置在屏幕中间?
If I have a HTML element with an unknown width and height, how can I centre it to exactly the middle of the screen?
如果纯CSS无法完成,那么javascript就可以了.
If it cannot be done with pure CSS, then javascript is OK.
推荐答案
此答案可能适合您的情况,也可能不适合您的情况,具体取决于确定未知宽度/高度的方式.如果 exact 尺寸未知,但设置了 percentages ,则可以使用以下技术:
This answer may or may not fit your situation, depending on how the unkown width/height are being determined. If the exact dimensions are unkown, but they are set with percentages, then you can use this technique:
#content {
background-color: khaki; /* demo purposes */
position: absolute;
height: 20%;
top: 50%;
margin-top: -10%; /* half the height */
width: 30%;
left: 50%;
margin-left: -15%; /* half the width */
}
有关示例,请参见此小提琴.总结一下:
See this fiddle for an example. To summarize:
- 限制:仅当确切尺寸未知(因为它们在%中指定)时才适用.
- 专业版:纯CSS解决方案.
- Con: only applicable if the exact dimensions are unkown because they are specified in %.
- Pro: pure CSS solution.
这篇关于将宽度未知的HTML元素居中到屏幕中间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文