我是否需要使用 "text-align" 以外的另一个 属性 来将我的 DIV 置于 DIV 的中心?
Do I need to use another property other than "text-align" to center my DIV within a DIV?
我想将 DIV 置于 parent DIV 的中心。我已经尝试在 SO 上使用推荐的解决方案——How to horizontally center a <div> in another <div>?,但它没有将它居中。基本布局是这样的
#revealScoreMobile {
padding: 10px;
display: block;
text-align: center;
width: 100%;
}
.stats {
text-align: center;
width: 100%;
background-color: red;
margin: 0 auto;
}
<div id="revealScoreMobile">
...
<div class="stats" style="">
<div class="score">5.0</div>
(<span class="votesCast">1</span> votes cast)
</div>
</div>
但是正如您从 Fiddle 中看到的 -- https://jsfiddle.net/5Lgu0uw3/2/,child DIV 没有在 parent 中居中,尽管事实上我有
text-align:center;
在那里。是什么赋予了?我还需要做些什么才能使 DIV 在其 parent 中居中?
正如其他人在评论中所建议的那样,text-align: center;
仅适用于文本内容,而不适用于内部 div
。
您的 CSS 将 width: 100%;
应用于 .stats
,这迫使它占据其父容器 #revealScoreMobile
的整个宽度,这也是 width: 100%;
.其次,它需要 display: inline-block;
来覆盖前面的 display: table-cell;
,如您的 jsfiddle 示例中所示。
在你的 CSS 中替换:
.stats {
display: inline-block;
text-align: center;
background-color: red;
margin: 0 auto;
}
我不完全确定你想要什么,但如果你想要内部 DIV 没有全宽,但只需要其文本内容所需的宽度,请将其设为 inline-block
并且擦除 width
设置(或将 width
设置设为小于 100%)。 inline-block
s 受到 text-align: center
的影响
(请注意,我删除了一些多余的设置,但将 ...
内容放入其自己的 DIV 中,否则它会与后续内联块位于同一行。
#revealScoreMobile {
padding: 10px;
text-align: center;
}
.stats {
display: inline-block;
text-align: center;
background-color: red;
}
<div id="revealScoreMobile">
<div> ... </div>
<div class="stats" style="">
<div class="score">5.0</div>
(<span class="votesCast">1</span> votes cast)
</div>
</div>
我想将 DIV 置于 parent DIV 的中心。我已经尝试在 SO 上使用推荐的解决方案——How to horizontally center a <div> in another <div>?,但它没有将它居中。基本布局是这样的
#revealScoreMobile {
padding: 10px;
display: block;
text-align: center;
width: 100%;
}
.stats {
text-align: center;
width: 100%;
background-color: red;
margin: 0 auto;
}
<div id="revealScoreMobile">
...
<div class="stats" style="">
<div class="score">5.0</div>
(<span class="votesCast">1</span> votes cast)
</div>
</div>
但是正如您从 Fiddle 中看到的 -- https://jsfiddle.net/5Lgu0uw3/2/,child DIV 没有在 parent 中居中,尽管事实上我有
text-align:center;
在那里。是什么赋予了?我还需要做些什么才能使 DIV 在其 parent 中居中?
正如其他人在评论中所建议的那样,text-align: center;
仅适用于文本内容,而不适用于内部 div
。
您的 CSS 将 width: 100%;
应用于 .stats
,这迫使它占据其父容器 #revealScoreMobile
的整个宽度,这也是 width: 100%;
.其次,它需要 display: inline-block;
来覆盖前面的 display: table-cell;
,如您的 jsfiddle 示例中所示。
在你的 CSS 中替换:
.stats {
display: inline-block;
text-align: center;
background-color: red;
margin: 0 auto;
}
我不完全确定你想要什么,但如果你想要内部 DIV 没有全宽,但只需要其文本内容所需的宽度,请将其设为 inline-block
并且擦除 width
设置(或将 width
设置设为小于 100%)。 inline-block
s 受到 text-align: center
(请注意,我删除了一些多余的设置,但将 ...
内容放入其自己的 DIV 中,否则它会与后续内联块位于同一行。
#revealScoreMobile {
padding: 10px;
text-align: center;
}
.stats {
display: inline-block;
text-align: center;
background-color: red;
}
<div id="revealScoreMobile">
<div> ... </div>
<div class="stats" style="">
<div class="score">5.0</div>
(<span class="votesCast">1</span> votes cast)
</div>
</div>