[英]text align:center is not doing well with width and display: inline-block
I am trying to have my text centered with a costum width. 我正在尝试使我的文字以Costum宽度为中心。 Setting the width or max width will restore the position of the line to left.
设置宽度或最大宽度会将线的位置恢复到左侧。 I am doing it like this:
我这样做是这样的:
I need to have custom width for each of them, have <h6>
and <a>
in one line and all of the content (including the border) in the middle. 我需要为它们中的每一个都具有自定义宽度,在一行中包含
<h6>
和<a>
,并将所有内容(包括边框)置于中间。
You need to set the parent of the h1
to text-align:center
您需要将
h1
的父级设置为text-align:center
body { text-align: center; } h1 { background: lightgreen; font-family: sans-serif; width: 200px; display: inline-block; }
<h1>Some text</h1>
/*without display: inline-block;*/ .h1{ text-align: center !important; font-family: sans-serif; width: 200px; margin: auto; } /*with display: inline-block;*/ .with_div{ text-align: center; } .with_div h1{ text-align: center !important; font-family: sans-serif; width: 200px; display: inline-block; }
<!-- without display: inline-block; --> <h1 class="h1">hello</h1> <!-- with display: inline-block --> <div class="with_div"> <h1>hello</h1> </div>
You can achieve this, regardless of whether it is in div or not with the CSS below. 您可以使用以下CSS来实现此目标,而不管它是否位于div中。 Similar to some of the others, but it also includes margin: auto;
与其他一些相似,但是它还包含margin:auto; which will center the h1 even if it is displayed as inline or inline-block.
即使将h1显示为行内或块内,它也将居中。
body{
text-align: center;
}
h1{
text-align: center !important;
font-family: sans-serif;
width: 200px;
margin: auto;
display: inline-block;
}
Without any wrapper div. 没有任何包装div。 CSS flex
CSS Flex
h1{
display:flex;
justify-content:center;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.