我希望整个块在其父块中居中,但我希望块的内容左对齐。
最好的例子
在本页面 :
ascii 艺术应该居中(如它所显示的那样),但它应该对齐并且看起来像“YAML”。
或这个 :
错误消息应该像在控制台中一样排列。
我希望整个块在其父块中居中,但我希望块的内容左对齐。
最好的例子
在本页面 :
ascii 艺术应该居中(如它所显示的那样),但它应该对齐并且看起来像“YAML”。
或这个 :
错误消息应该像在控制台中一样排列。
首先,创建一个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>
如果您希望确保长线不会将所有内容加宽太多,您还可以将max-width
属性(具有您选择的值)应用于内部标签:
max-width: 250px;
重新发布另一个问题的工作答案:如何将可变宽度的浮动元素水平居中?
假设浮动并居中的元素是一个 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的一个很好的参考
如果我理解你,你需要使用来居中一个容器(或块)
margin-left: auto;
margin-right: auto;
并左对齐其内容:
text-align: left;
我发现在容器内居中和左对齐文本的最简单方法如下:
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 上使用 margin: 0 auto ,但是您必须为 div 指定宽度。如果您不想指定宽度,也可以(这取决于您要执行的操作)使用边距,例如 margin: 0 200px; ,这应该使您的内容看起来好像是居中的,您还可以看到Leyu对我的问题的回答
<div>
<div style="text-align: left; width: 400px; border: 1px solid black; margin: 0 auto;">
<pre>
Hello
Testing
Beep
</pre>
</div>
</div>
这是你想要的?弹性盒...
.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>
对于我们这些仍在使用旧浏览器的人,这里有一些扩展的向后兼容性:
<div style="text-align: center;">
<div style="display:-moz-inline-stack; display:inline-block; zoom:1; *display:inline; text-align: left;">
Line 1: Testing<br>
Line 2: More testing<br>
Line 3: Even more testing<br>
</div>
</div>
部分受到这篇文章的启发:https ://stackoverflow.com/a/12567422/14999964 。
这行得通
<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>