题
我希望整个块位于其父级的中心,但我希望块的内容左对齐。
例子最有效
在本页 :
ascii 艺术应该居中(正如它所显示的那样),但它应该对齐并且看起来像“YAML”。
或这个 :
错误消息应该像在控制台中一样全部排列起来。
解决方案 2
重新发布另一个问题的工作答案: 如何将可变宽度的浮动元素水平居中?
假设浮动且居中的元素是一个 id="content" 的 div ...
<body>
<div id="wrap">
<div id="content">
This will be centered
</div>
</div>
</body>
并应用以下 CSS
#wrap {
float: left;
position: relative;
left: 50%;
}
#content {
float: left;
position: relative;
left: -50%;
}
这是一个很好的参考 http://dev.opera.com/articles/view/35-floats-and-clearing/#centeringfloats
其他提示
首先,创建一个中心及其子含量div
父text-align: center
。接下来,创建使用div
适应其子的宽度和display: inline-block
使其保持靠左对齐,如需要的话。
text-align: left
<div style="text-align: center;">
<div style="display: inline-block; text-align: left;">
Centered<br />
Content<br />
That<br />
Is<br />
Left<br />
Aligned
</div>
</div>
如果我明白你好,则需要使用到中心容器(或块)
margin-left: auto;
margin-right: auto;
和左对齐它的内容:
text-align: left;
通常你应该使用保证金:正如其他答案中提到的,div 上的 0 auto ,但您必须指定 div 的宽度。如果您不想指定宽度,您也可以(这取决于您想要做什么)使用边距,例如边距:0 200 像素;,这应该会让你的内容看起来像是居中的,你也可以看到Leyu的回答 我的问题
<div>
<div style="text-align: left; width: 400px; border: 1px solid black; margin: 0 auto;">
<pre>
Hello
Testing
Beep
</pre>
</div>
</div>
这是你在找什么? Flexbox的...
.container{
display: flex;
flex-flow: row wrap;
justify-content: center;
align-content: center;
align-items: center;
}
.inside{
height:100px;
width:100px;
background:gray;
border:1px solid;
}
<section class="container">
<section class="inside">
A
</section>
<section class="inside">
B
</section>
<section class="inside">
C
</section>
</section>
我发现居中最简单的方法和在容器内左对齐文本如下:
HTML:
<div>
<p>Some interesting text.</p>
</div>
CSS:
P {
width: 50%; //or whatever looks best
margin: auto; //top and bottom margin can be added for aesthetic effect
}
希望这是你要找的人,因为我花了相当多的搜索只是为了弄清楚这个很基本的解决方案。
此工作原理
<div style="display:inline-block;margin:10px auto;">
<ul style="list-style-type:none;">
<li style="text-align:left;"><span class="red">❶</span> YouTube AutoComplete Keyword Scraper software <em>root keyword text box</em>.</li>
<li style="text-align:left;"><span class="red">❷</span> YouTube.com website <em>video search text box</em>.</li>
<li style="text-align:left;"><span class="red">❸</span> YouTube AutoComplete Keyword Scraper software <em>scraped keywords listbox</em>.</li>
<li style="text-align:left;"><span class="red">❹</span> YouTube AutoComplete Keyword Scraper software <em>right click context menu</em>.</li>
</ul>
</div>
不隶属于 StackOverflow