我想让我的链接在屏幕水平方向上居中,我该如何做到这一点?
<a href="http://www.example.com">example</a>
text-align
CSS 属性。<div style="text-align:center">
<a href="http://www.example.com">example</a>
</div>
或使用类(推荐)
<div class="my-class">
<a href="http://www.example.com">example</a>
</div>
.my-class {
text-align: center;
}
.my-class {
text-align: center;
background:green;
width:400px;
padding:15px;
}
.my-class a{text-decoration:none; color:#fff;}
<!--EXAMPLE-ONE-->
<div style="text-align:center; border:solid 1px #000; padding:15px;">
<a href="http://www.example.com">example</a>
</div>
<!--EXAMPLE-TWO-->
<div class="my-class">
<a href="http://www.example.com">example</a>
</div>
问: 为什么text-align
样式没有应用于a
元素,而是应用于div
元素?
答: text-align
样式描述了如何在块级元素
中对内联元素
进行对齐。在这种情况下,div
是一个块级元素,它的内联内容是a
元素。如果将text-align
样式应用于伴随其他文本的a
元素,这样做就毫无意义了。
<div>
Plain text is inline content.
<a href="http://www.example.com" style="text-align: center">example</a>
<span>Spans are also inline content</span>
</div>
div
的所有内容都是内联内容,因此会产生类似以下的内容:text-align
属性,很难理解在这种情况下“示例”将如何显示。div
是块级元素,a
是内联内容。 - JaredMcAteer.my-class { ... }
改为 div, a {...}
并保持相同的内容,这个修改是有效的吗? - Manuel Jordandiv, a {...}
将会将样式规则应用于您代码中的所有 div 和 anchor 元素,而不考虑结构。 - JaredMcAteer像这样编写:
<div class="parent">
<a href="http://www.example.com">example</a>
</div>
CSS
.parent{
text-align:center
}
有两个选项,它们具有不同的用途:
HTML:
<a class="example" href="http://www.example.com">example</a>
CSS:
.example { text-align: center; }
或者:.example { display:block; width:100px; margin:0 auto;}
尝试:
margin: 0 auto;
display: table
div
)。 - dash尝试在周围包裹一个div
,并为div
添加这些样式:
width: 100%;
text-align: center;
<span style="text-align:center; display:block;">
<a href="http://news.awaissoft.com">Awaissoft</a>
</span>
默认情况下,锚点是以行内方式呈现的,因此请在其最近的块级祖先上设置text-align: center;
。
我认为您无法使用内联元素(如锚点、span)来实现此功能。但是,要使其正常工作,您需要将显示设置为块级元素。
<a href="http://www.example.com" style="text-align:center;display:block;">example</a>
有很多种方法。
<!-- Probably the most common: -->
<div style="text-align: center;"><a href="...">Link</a></div>
<!-- Getting crafty... -->
<a href="..." style="display: block; text-align: center;">Link</a></div>
可能还有其他方法,但这三种可能是最常见的。
/**code starts here**/
a.class_name { display : block;text-align : center; }