我知道这已经详细讨论了,但我似乎无法找到解决这个问题的答案。这是一个简单的例子来说明我的问题。我在父div
中有两个子div
元素,我希望它们在父div
内水平居中。这是小提琴:
#container {
position: relative;
float: none;
margin: 0 auto;
border: solid blue 1px;
width: 100%;
}
.tile {
width: 20em;
height: 40em;
border:solid black 1px;
display: inline-block;
margin: 1.5em auto;
}

<div id="container">
<div class="tile">
<!--
When you remove this comment, the div shifts down and I do not understand what is causing that.
<h3>This Title Moves the div down. Why?</h3>-->
</div>
<div class="tile"></div>
</div>
&#13;
现在有一个我想念的简单解决方案吗?此外,我还有关于h3
标记的次要问题。删除h3
标记周围的评论后,第一个div
会向下移动。 h3
标记会导致div
向下移动,如何防止它发生?
感谢您的回答和帮助,我为可能的重复问题道歉。
答案 0 :(得分:2)
您可以添加:.title {display:block; }
#container {
position: relative;
float: none;
margin: 0 auto;
border: solid blue 1px;
width: 100%;
}
.tile {
border: 1px solid black;
display: block;
height: 40em;
margin: 1.5em auto;
width: 20em;
text-align:justify;
padding:7px;
}
h3 {
margin: 0;
padding: 0;
}
&#13;
<div id="container">
<div class="tile">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
</div>
<div class="tile">
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.
</div>
</div>
&#13;
答案 1 :(得分:1)
您可以将margin:auto
添加到.tile
,将text-align:center
添加到#container
#container {
position: relative;
float: none;
margin: 0 auto;
border: solid blue 1px;
width: 100%;
text-align: center;
}
.tile {
width: 20em;
height: 40em;
border:solid black 1px;
display: inline-block;
margin: auto;
}
<div id="container">
<div class="tile">
<h3>This Title Moves the div down. Why?</h3>
</div>
<div class="tile"></div>
</div>
答案 2 :(得分:1)
将以下代码添加到#container
:
display: flex;
justify-content: center;
align-items: center;
直播片段
#container {
position: relative;
float: none;
margin: 0 auto;
border: solid blue 1px;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.tile {
width: 20em;
height: 40em;
border:solid black 1px;
display: inline-block;
margin: 1.5em 0;
}
&#13;
<div id="container">
<div class="tile">
<!--
When you remove this comment, the div shifts down and I do not understand what is causing that.
<h3>This Title Moves the div down. Why?</h3>-->
</div>
<div class="tile"></div>
</div>
&#13;
答案 3 :(得分:0)
默认使用display:inline-block
为vertical-align: bottom;
,以便将.tile
设置为vertical-align: middle;
,将text-align:center
设置为#container
.tile {
width: 20em;
height: 40em;
border:solid black 1px;
display: inline-block;
margin: 1.5em auto;
vertical-align: middle;
}
答案 4 :(得分:0)
` `
#container {
padding:25%;
text-align:center;
background:#e7e7e7;
}
.tile{
background:white;
display:inline-block;
padding:20%;
}
<div id="container">
<div class="tile">
<h3>This Title Moves the div down. Why?</h3>
</div>
<div class="tile"></div>
</div>