为什么设置CSS text-align属性后文本无法正常对齐?
问题原因
- HTML结构严重非法:代码中重复定义了两套完整的
<html>根文档结构,出现多次<!DOCTYPE html>、<head>、<body>标签,还存在标签错位闭合问题。浏览器解析此类非法结构时会触发不确定的容错逻辑,大概率导致你写在外部css中的h1样式无法正确作用到目标元素,甚至出现样式覆盖错乱。 - 父级容器宽度被限制:你在内部样式中给全局
body设置了width: 100px,就算h1设置了width: 100%,也只能继承到100px的可用宽度,而你给h1设置的字号达到112px,单个文字宽度已经超过容器宽度,自然看不出居中效果。 - 样式引入路径不匹配:你写的h1相关样式是放在外部
style.css文件中,该文件仅在第一套无效的HTML结构中被引入,包含h1标签的第二套HTML结构并没有加载对应的外部样式,所以你设置的text-align: center根本没有生效。
修复方案
- 规整HTML结构,全局只保留一组
<!DOCTYPE html>、<html>、<head>、<body>标签,所有资源引入、meta配置统一放在head标签内,所有页面内容放在body标签内。 - 移除body上的
width: 100px限制,如果你需要给指定动画色块设置宽高,单独给对应div定义类名加样式,不要限制全局body的宽度。 - 把h1的样式统一放到HTML内部的style标签中,或者确保外部style.css在当前文档的head中正确引入,保证样式可以命中目标h1元素。
修复后示例代码
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>e</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> @import url('https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap'); /* 背景图样式 */ img.bg { min-height: 100%; min-width: 104px; width: 100%; height: auto; position: fixed; top: 0; left: 0; z-index: -1; } h1 { font-family: 'Source Sans Pro', sans-serif; color: white; text-shadow: 0px 0px 40px #690000; font-size: 112px; padding-bottom: 20px; text-align: center; display: block; width: 100%; } /* 动画色块单独加类名设置样式 */ .animate-block { width: 100px; height: 100px; background-color: red; animation-name: example; animation-iteration-count: infinite; animation-duration: 2s; animation-direction: alternate; } @keyframes example { from {background-color: red;} to {background-color: orange;} } </style> </head> <body> <h1>Denied</h1> <div class="animate-block"></div> <script src="script.js"></script> </body> </html>
内容的提问来源于stack exchange,提问作者TymeFlys
相关产品推荐
相关产品推荐

