Html 麻烦(垂直)在另一个 DIV 中居中文本与相对 % 大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13994549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trouble (vertically) Centering Text in another DIV with relative % sizing
提问by cirrus
Disclaimer:I don't believe this is a duplicate as I'm using relative sizes to produce a full screen grid layout without using px
.
免责声明:我不认为这是重复的,因为我使用相对大小来生成全屏网格布局而不使用px
.
Problem:In this jsFiddle http://jsfiddle.net/X3ZDy/73/I have four equally proportioned boxes. They are designed to span the screen width and remain square. Contained within them are some sample square DIVs (40% x 40%). I'm struggling though to get a text label lbl
horizontally and vertically centered within bbl
.
问题:在这个 jsFiddle http://jsfiddle.net/X3ZDy/73/我有四个等比例的盒子。它们旨在跨越屏幕宽度并保持方形。其中包含一些示例方形 DIV (40% x 40%)。我正在努力获得一个lbl
水平和垂直居中的文本标签bbl
。
All the examples I've seen (and tried) don't work as they require me to know the height of my label, or they use browser restricted table-layout
tricks. I need to do this with all relative sizes as per the fiddle.
我见过(并尝试过)的所有示例都不起作用,因为它们要求我知道标签的高度,或者它们使用浏览器限制的table-layout
技巧。我需要按照小提琴使用所有相对大小来执行此操作。
Can anyone assist? I need to this to work on ALL browsers with a pure CSS (no JS) solution. I'm astonished that it appears to be quite so tricky to vertically align text in a div. I don't mind if we use block or inline elements as the text label.
任何人都可以提供帮助吗?我需要这样做才能在所有具有纯 CSS(无 JS)解决方案的浏览器上工作。我很惊讶在 div 中垂直对齐文本似乎非常棘手。我不介意我们使用块元素还是内联元素作为文本标签。
Please note that I'm NOT looking for a TABLE solution, this is a DIV & CSS puzzle that requires a working jsFiddle.
请注意,我不是在寻找 TABLE 解决方案,这是一个需要使用 jsFiddle 的 DIV 和 CSS 拼图。
More:Thanks all for your answers, but for future posters, note that (width == padding-bottom) is the magic that allows my DIVs to be square. It's key to a grid-layout system so I need to maintain that.
更多:感谢大家的回答,但对于未来的海报,请注意 (width == padding-bottom) 是让我的 DIV 成为square的魔法。这是网格布局系统的关键,所以我需要维护它。
updatedIt's pretty tricky working with relative sizes and no fixed heights, but I think I've finally found an answer to the problem (below).
更新使用相对尺寸且没有固定高度非常棘手,但我想我终于找到了问题的答案(如下)。
回答by cirrus
I think I finally found an answer to the problem that works. The issue is that almost every other solution I've seen can't cope when the child size changes and none of the heights are known. I needed this to work for a responsive all % design where there are no fixed heights anywhere.
我想我终于找到了有效的问题的答案。问题是我见过的几乎所有其他解决方案都无法应对当孩子大小发生变化并且不知道任何身高时。我需要它来实现响应式全 % 设计,其中任何地方都没有固定高度。
I stumbled across this SO answer Align vertically using CSS 3which was my inspiration.
我偶然发现了这个 SO 答案使用 CSS 3 垂直对齐,这是我的灵感。
Firstly, using an all % design, you need a zero height wrapper element to act as a positioning placeholder within the parent element;
首先,使用全 % 设计,您需要一个零高度包装元素作为父元素内的定位占位符;
<body>
<div class="container">
<div class="divWrapper">
<div class="tx">This text will center align no matter how many lines there are</div>
</div>
</div>
</body>
My Container in this case is a simple box tile;
在这种情况下,我的容器是一个简单的盒子瓷砖;
.container
{
margin:2%;
background-color:#888888;
width:30%;
padding-bottom:30%; /* relative size and position on page */
float: left;
position:relative; /* coord system stop */
top: 0px; /* IE? */
}
So nothing special about that except that it has no heightwhich makes this general problem of centering elements tricky. It needs to be absolutely positioned so that we can uses positioning coordinates in the child elements (I think this may require a 'top' in IE).
所以没有什么特别之处,只是它没有高度,这使得居中元素的一般问题变得棘手。它需要绝对定位,以便我们可以在子元素中使用定位坐标(我认为这可能需要 IE 中的“顶部”)。
Next, the wrapper which is absolutelypositioned to exactly overlay the parent element and fill it out completely.
接下来,绝对定位以完全覆盖父元素并完全填充它的包装器。
.divWrapper
{
position:absolute;
top:0px;
padding-top:50%; /* center the top of child elements vetically */
padding-bottom:50%;
height:0px;
}
The padding means that any child elements will start in exactly the middle of the parent elementbut this wrapper itself has no height and takes up no space on the page.
填充意味着任何子元素都将从父元素的中间开始,但是这个包装器本身没有高度,也不占用页面上的空间。
Nothing new yet.
还没有什么新东西。
Finally, the child element we want to center. The trick here to this was to have the child element slide up vertically based on it's own height. You can't use 50%, because that's 50% of the parent container not ourself. The deceptively simple answer is to use a transform. I can't believe I didn't spot this before;
最后,我们要居中的子元素。这里的技巧是让子元素根据它自己的高度垂直向上滑动。你不能使用 50%,因为那是父容器的 50% 而不是我们自己。看似简单的答案是使用变换。我不敢相信我以前没有发现这一点;
.tx
{
position: relative;
background-color: transparent;
text-align: center; /* horizontal centering */
-webkit-transform: translateY(-50%); /* child now centers itself relative to the midline based on own contents */
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-ms-filter: 'progid:DXImageTransform.Microsoft.Matrix(M11=0.5, M12=0, M21=0, M22=0.5, SizingMethod="auto expand")'; /*IE8 */
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.5, M12=0, M21=0, M22=0.5, SizingMethod='auto expand'); /*IE6, IE7*/
transform: translateY(-50%);
}
Here's the Fiddle
这是小提琴
However, I haven't tested this on IE6+ so if somebody would like to verify my Matrix transform I'd appreciate it.
但是,我还没有在 IE6+ 上测试过这个,所以如果有人想验证我的矩阵变换,我会很感激。
Update
更新
It turns out that the wrapper isn't even needed. This is all you need to properly vertically center;
事实证明,甚至不需要包装器。这就是正确垂直居中所需的全部内容;
.tx
{
width:100%; // +1 to @RonM
position: absolute;
text-align: center;
padding-top:100%;
-webkit-transform: translateY(-50%); /* child now centers itself relative to the midline based on own contents */
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-o-transform: translateY(-50%);
-ms-filter: 'progid:DXImageTransform.Microsoft.Matrix(Dx=0,Dy=0)'; /*IE8 */
filter: progid:DXImageTransform.Microsoft.Matrix(Dx=0,Dy=0); /*IE6, IE7*/
transform: translateY(-50%);
}
And the updated Fiddle
和更新的小提琴
But still not working in IE6 yet - looking at those transforms, I don't think this can be done for that legacy without JavaScript.
但仍然不能在 IE6 中工作 - 看看这些转换,我认为没有 JavaScript 就无法为遗留系统做到这一点。
回答by Jani Hyyti?inen
The reality is, that the only tags in HTML that have native fluid vertical alignment are the table cells.
现实情况是,HTML 中唯一具有原生流体垂直对齐的标签是表格单元格。
CSS does not have anything that would get you what you want. Not today.
CSS 没有任何东西可以让你得到你想要的东西。今天不行。
If the requirements are: 1. Works with every browser 2. fluid height 3. vertical centering 4. no scripting 5. No TABLEs 6. You want the solution today, not in few years
如果要求是: 1. 适用于所有浏览器 2. 流体高度 3. 垂直居中 4. 没有脚本 5. 没有表格 6. 您想要今天的解决方案,而不是几年后
You are left with 1 option: 1. Drop ONE of your requirements
您只剩下 1 个选项: 1. 删除您的一项要求
Otherwise this "puzzle" is not completable. And this is the only complete acceptable answer to your request.
否则这个“谜题”是无法完成的。这是对您的请求唯一完全可以接受的答案。
... if only I could get all the salaries for the wasted hours on this particular challenge :)
...如果我能在这个特殊的挑战中获得所有浪费时间的工资就好了:)
回答by tiffon
Don't self-abuse; let IE7 go... :) (According to this, not very many people are using it.)
不要自虐;让 IE7 走... :) (根据this,使用它的人并不多。)
I gave this a shot with two approaches, one uses display: table
and the other uses line-height
. Unfortunately, I don't have access to a PC, so they're only tested in Chrome 25.0.1365.1 canary, FF 18, and Safari 6.0 on Mac 10.8.1, iOS 6.0.1 Safari, and iOS Simulator 5.0 and 5.1 Safari.
我用两种方法试了一下,一种使用display: table
,另一种使用line-height
。不幸的是,我无法访问 PC,因此它们仅在 Mac 10.8.1、iOS 6.0.1 Safari 和 iOS Simulator 5.0 和 5.1 Safari 上的 Chrome 25.0.1365.1 canary、FF 18 和 Safari 6.0 中进行了测试.
The display: table
approach has issues on iOS Simulator 5.0 and 5.1, the text isn't quite centered, vertically.
该display: table
方法在 iOS Simulator 5.0 和 5.1 上存在问题,文本没有完全垂直居中。
According to quirksmode, the display:table
method should be compatitible with IE8 and up. Theorectically, the line-height method mightbe compatible with IE 6/7.
根据quirksmode,该display:table
方法应该与 IE8 及更高版本兼容。理论上,line-height 方法可能与 IE 6/7 兼容。
To create the centered box within each square, I set .box6
to position: relative
and changed the .bc
style to:
为了在每个正方形内创建居中的框,我将样式设置.box6
为position: relative
并将.bc
样式更改为:
.bc {
position:absolute;
top: 30%;
bottom: 30%;
left: 30%;
right: 30%;
overflow: hidden;
}
Each approach creates a very tall container with a static height inside the .bc
element. The exact value for the static height is arbitrary, it just needs to be taller than the content it will contain.
每种方法都会创建一个非常高的容器,在.bc
元素内部具有静态高度。静态高度的确切值是任意的,它只需要比它将包含的内容高。
The display: table
method changes the .bbl
and .bbl .lbl
styles to:
该display: table
方法将.bbl
和.bbl .lbl
样式更改为:
.bbl {
display: table;
height: 500px;
padding-top: 50%;
margin-top: -250px;
background-color: blanchedalmond;
width: 100%;
}
.bbl .lbl {
display: table-cell;
vertical-align: middle;
text-align:center;
}
For the line-height
method, the HTML is:
对于该line-height
方法,HTML 是:
<div class="bc">
<div id="line-h-outter">
<span id="line-h-inner">a lot more text than in the other blob. The quick brown fox jumped over the lazy dog</span>
</div>
</div>
CSS:
CSS:
#line-h-outter {
line-height: 500px;
vertical-align: middle;
margin-top: -250px;
padding-top: 50%;
}
#line-h-inner {
display: inline-block;
line-height: normal;
vertical-align: middle;
text-align: center;
width: 100%;
}
回答by Jimmy Kane
The title should be Centering in the Unknown;-)
I updated your example using tables: http://jsfiddle.net/uWtqY/and the text is align inside the box you described using tables, but you don't want this.
我使用表格更新了您的示例:http: //jsfiddle.net/uWtqY/并且文本在您使用表格描述的框中对齐,但您不想要这个。
Added a table with like:
添加了一个表,例如:
<table width="100%" height="100%"><tr><td>One line</td></tr> </table></div>
inside <div class="lbl">
里面 <div class="lbl">
Just for cross-browser support.
仅用于跨浏览器支持。
EDIT
编辑
After doing some research indeed it is really hard to v-align an element inside percentages. Tried a lot of stuff but your code I am not sure if it fits the design of all of them. Well what I mean in other words is that you might first need to construct your vertical alignment and then try to play with percentages. From my experience in this field I learned that a good approach is start designing from the inside elements and then go out if complexity increases. So having percentages in everything might not be the best implementation (and it is not when coming to mobile devices).
在做了一些研究之后,确实很难在百分比内对元素进行 v-align。尝试了很多东西,但你的代码我不确定它是否适合所有的设计。换句话说,我的意思是您可能首先需要构建垂直对齐方式,然后尝试使用百分比。根据我在该领域的经验,我了解到一个好的方法是从内部元素开始设计,然后在复杂性增加时退出。因此,在所有内容中都使用百分比可能不是最佳实现(而且在移动设备上也不是)。
EDIT 2
编辑 2
After consolidating with several of my work partners and really geeks on the area of HTML the answer was clear. Either you support < IE7 and you do that with a table or ghost elements or spans, either you use all of the tequniques that are described in several posts and you can have support for >=IE7 . Another option is to use specific structure for each browser.
在与我的几个工作伙伴和 HTML 领域的真正极客合并后,答案很清楚。要么支持 < IE7 并使用表格或幽灵元素或跨度执行此操作,要么使用多篇文章中描述的所有 tequniques 并且可以支持 >=IE7 。另一种选择是为每个浏览器使用特定的结构。
The link that I think explains it as it is and has a nice title (basically is what you need):
我认为的链接按原样解释了它并且有一个很好的标题(基本上就是你需要的):
->以未知为中心
Hope the best.
希望最好。
PS. Links for reference:
附注。参考链接:
Let me know if it helps
让我知道它是否有帮助
回答by helvete
Today I have stumbled upon similar problem - to both vertically and horizontally center child element of a square divs which have precentually set width (they are made sqare using the padding technique). I had to use it for images while maintaining aspect ratio, but changing the child into any target element would be simple.
今天,我偶然发现了类似的问题 - 一个方形 div 的垂直和水平居中的子元素,这些子元素预先设置了宽度(它们是使用填充技术制作的方形)。我不得不在保持纵横比的同时将它用于图像,但是将子元素更改为任何目标元素会很简单。
For this situation no line-height, margin/padding or display:table-cell workaround is suitable. But there is a solution using margin: auto
.
对于这种情况,没有行高、边距/填充或显示:表格单元格解决方法是合适的。但是有一个解决方案使用margin: auto
.
HTML:
HTML:
<div class="squareContainer>
<div class="contentWrapper">
<img class="imagePreview" alt="Image preview" src="//URL.jpg">
</div>
</div>
CSS:
CSS:
div.squareContainer {
position: relative;
box-sizing: border-box;
height: 0;
padding-bottom: 25%;
width: 25%;
}
div.contentWrapper {
position: absolute;
bottom: 0;
left: 0;
right: 0;
top: 0;
}
img.imagePreview {
display: block;
position: absolute;
bottom: 0;
left: 0;
right: 0;
top: 0;
margin: auto; /* This is the important line */
max-height: 90%;
max-width: 90%;
}
Helpful resources:
有用的资源:
http://codepen.io/HugoGiraudel/pen/ucKEC
http://codepen.io/HugoGiraudel/pen/ucKEC
Hope that helps!
希望有帮助!
回答by fyngyrz
You can solve this trivially, without all the weirdness (perhaps someday they'll fix the CSS box model, but till then):
你可以简单地解决这个问题,没有所有的奇怪(也许有一天他们会修复 CSS 框模型,但在那之前):
<table>
<tr>
<td width="50" height="50" align="center" valign="middle">text</td>
</tr>
</table>
That's all there is to it. Choose your width and height, drop it in a div and call it good.
这里的所有都是它的。选择您的宽度和高度,将其放入一个 div 中并称其为好。
The idea of never using tables is a very poor guideline, to the point of being self-abusive.
从不使用表格的想法是一个非常糟糕的指导方针,甚至是自虐。
回答by Kevin Whatever
I updated the css to utilize a "spacer" class. It is placed before your "bc" div and inside the colored boxes. This gave me the effect I think you requested.
我更新了 css 以利用“间隔”类。它位于“bc”div 之前和彩色框内。这给了我我认为你要求的效果。
html:
<div class="rgCol boxCol box6" style="background-color:lightgray">
<div class="spacer"></div>
<div class="bc">
css
.spacer {width:100%;padding-bottom:30%;display:block; }
I bottom padded the spacer by 30% and then moved the absolute left position of your "bbl" div to 30% (from 2%). The blanchdelemond boxes retain their shape and size.
我底部填充了 30% 的垫片,然后将“bbl”div 的绝对左侧位置移动到 30%(从 2%)。blanchdelemond 盒子保持其形状和大小。
回答by Zeddy
Do you mean like this?
你的意思是这样吗?
<div class="mycontainer">
<div class="rgRow">
<div class="rgCol" style="background-color:pink">
<div class="boxCol">BOX1</div>
</div>
<div class="rgCol" style="background-color:lightgray">
<div class="boxCol">
<div class="boxLabel">a lot more text than in the other blob. The quick brown fox jumped over the lazy dog</div>
</div>
</div>
<div class="rgCol" style="background-color:maroon">
<div class="boxCol">
<div class="boxLabel">One liner</div>
</div>
</div>
<div class="rgCol" style="background-color:yellow">
<div class="boxCol">BOX4</div>
</div>
</div>
</div>
.mycontainer
{
background-color: #000000;
display: inline-table;
}
.rgRow
{
width: 100%;
display: table-row;
}
.rgCol
{
width: 25%;
height: 100%;
text-align: center;
vertical-align: middle;
display: table-cell;
}
.boxCol
{
display: inline-block;
width: 100%;
text-align: center;
vertical-align: middle;
}
.boxLabel
{
text-align: center;
vertical-align: middle;
background-color: blanchedalmond;
overflow: hidden;
margin: 2%;
width: 96%;
height: 96%;
}