CSS内联块中心内容



我有2个问题,下面CSS

#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,output

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

  2. 为什么盒子之间有GAB?

卸下填充物。添加line-height: 50px;

盒子之间的缝隙是HTML中的物理空间。使父 font-size: 0

只需将 float: left;添加到您的#calendarWrap div,然后将填充物更改为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替换填充物,在您发送的链接中,编辑器在输入按钮时似乎会自动空间。

要删除元素之间的空间,请删除元素之间的空白。由于这些是inline-block(被视为inline),它们将在块之间和之间保留空白。如果您想水平和垂直将这些盒子内的内容集中在这些框中,最简单的方法可能是应用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;。这更可重复。

#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>

最新更新