繁体   English   中英

在固定大小div的中间对齐范围

[英]align span in the middle of a fixed size div

我有一个固定尺寸的div和背景图片,并且我希望文本直接在中间对齐。 垂直和水平。

我能够进行水平对齐,但是我一生都无法使其垂直对齐。 我在这里看到了答案,但找不到适用于固定大小div的任何内容。

您可以看到跨度周围的蓝色边框。 如果我可以将其向下移动以始终以任何文本为中心(只要它不会变得太大),我就会在那里。

 div { background-image: url(http://i.imgur.com/I86rTVl.jpg); width: 500px; height: 300px; border: 1px solid red; } span { position: absolute; text-align: center; width: 500px; border: 1px solid blue; font-size: 72px } 
 <body> <div> <span>Testing for fiddle</span> </div> </body> 

在许多可能的解决方案中,这是一种现代的flexbox技术。

检查浏览器兼容性表中的Flexbox

 div { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; /* Center vertically */ background-image: url("http://i.imgur.com/I86rTVl.jpg"); border: 1px solid red; height: 300px; width: 500px; } span { /* position: absolute; Remove */ white-space: nowrap; /* Avoid text wrapping */ text-align: center; width: 500px; border: 1px solid blue; font-size: 72px } 
 <body> <div> <span>Testing for fiddle</span> </div> </body> 

尝试使用良好的旧表/表单元格技术。 向下工作到IE9 :)

 div { background-image: url(http://i.imgur.com/I86rTVl.jpg); width: 500px; height: 300px; border: 1px solid red; display:table; } span { display:table-cell; text-align: center; width: 100%; vertical-align:middle; border: 1px solid blue; font-size: 72px } 
 <body> <div> <span>Testing for fiddle</span> </div> </body> 

绝对定位

将父级设置为position:relative将子级的位置设置为top:50%,并将其平移回它自身高度的一半。

 div { background-image: url(http://i.imgur.com/I86rTVl.jpg); width: 500px; height: 300px; border: 1px solid red; position: relative; } span { position: absolute; text-align: center; width: 500px; top: 50%; left: 0%; transform: translateY(-50%); border: 1px solid blue; font-size: 72px } 
 <body> <div> <span>Testing for fiddle</span> </div> </body> 

https://jsfiddle.net/kvqLnchw/1/

  div {
    background: url(http://i.imgur.com/I86rTVl.jpg) no-repeat;
    width:500px;
    height: 300px;
    border: 1px solid red;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align:center;
}

span {

    border: 1px solid blue;
    font-size: 72px

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM