繁体   English   中英

CSS内联块居中内容

[英]css inline-block centering content

我在css下面有2个问题

#calendarWrap div{
        display: inline-block;
        width: 50px;
        height: 50px;
        background: white;
        border: 1px solid black;
        text-align: center;
        padding: 30px;  
}

* {
  box-sizing:border-box;
}

https://jsbin.com/bononudiju/edit?html,css,输出

  1. 为什么内容不完全居中? 它稍微下降到了底部,应该稍微上升一点。 我必须手动调整位置吗? 我知道我可以使用相对位置,但是无论高度和宽度如何,都可以使它居中吗?

  2. 盒子之间为什么有空隙?

除去填充物。 添加line-height: 50px;

框之间的间隙是HTML中的物理空间。 设置父font-size: 0

只需添加float: left; 到您的#calendarWrap div并将padding更改为padding: 15px 0;

要消除差距,请尝试以下操作:

<div id="calendarWrap">
    <div>1</div><!--
 --><div>2</div><!--
 --><div>3</div><!--
 --><div>4</div><!--
 --><div>5</div>
</div>

您可以尝试以下方法:

 #calendarWrap div{ display: inline-block; width: 50px; height: 50px; background: white; border: 1px solid black; text-align: center; line-height:50px; } * { box-sizing:border-box; } 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div id="calendarWrap"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> </div> </body> </html> 

基本上,将填充替换为line-height然后在您发送的链接中,当您按下Enter键时,编辑器似乎会自动调整空间。

要删除元素之间的空间,请删除元素之间的空白。 由于这些是inline-block (被视为inline ),因此它们将保留块内和块之间的空白。 而且,如果您想水平和垂直地将这些框内的内容居中,则最简单的方法可能是应用display: inline-flex; align-items: center; justify-content: center; display: inline-flex; align-items: center; justify-content: center;

 #calendarWrap div{ display: inline-flex; width: 50px; height: 50px; background: white; border: 1px solid black; padding: 30px; align-items: center; justify-content: center; } * { box-sizing:border-box; } 
 <div id="calendarWrap"> <div>1</div><div>2</div><div>3</div><div>4</div><div>5</div> </div> 

我建议您使用display:table-cell; vertical-align:middle; text-align:center; display:table-cell; vertical-align:middle; text-align:center; 那是更可重复的。

 #calendarWrap>div{ display:table-cell; vertical-align:middle; width:50px; height:50px; text-align:center; border:#000 solid 1px; border-left:0; } #calendarWrap>div:first-child{ border-left:#000 solid 1px; } 
 <!DOCTYPE html> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'> <head> <meta http-equiv='content-type' content='text/html;charset=utf-8' /> <title>display centered</title> </head> <body> <div id='calendarWrap'> <div>1</div><div>2</div><div>3</div><div>4</div><div>5</div> </div> </body> </html> 

暂无
暂无

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

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