我有一些文本元素(h1
),由于某些原因它们都是相同的宽度,即使它们中有不同的文本。
HTML:
<h1 class="main-text" id="one">text</h1>
<h1 class="main-text" id="two">texttextext</h1>
<h1 class="main-text" id="three">texttextexttexttextext</h1>
CSS:
.main-text {
position: relative;
left: 50%;
transform: translate(-50%, 0);
text-align: center;
color: #848484;
font-family: "Roboto";
font-size: 40px;
}
出于某种原因,当我运行以下JS代码时:
console.log(document.getElementById("one").offsetWidth)
console.log(document.getElementById("two").offsetWidth)
console.log(document.getElementById("three").offsetWidth)
所有这些都记录为23
。我的屏幕宽度是1920px,如果这有帮助。我的CSS中是否有可能导致此问题的内容?
h
是一个块级元素,因此它会尝试占用父级的全宽
使用display:inline-block
根据内容设置宽度,使用<br/>
换行
console.log(document.getElementById("one").offsetWidth)
console.log(document.getElementById("two").offsetWidth)
console.log(document.getElementById("three").offsetWidth)
.main-text {
position: relative;
left: 50%;
transform: translate(-50%, 0);
text-align: center;
color: #848484;
font-family: "Roboto";
font-size: 40px;
display: inline-block;
}
<h1 class="main-text" id="one">text</h1>
<br/>
<h1 class="main-text" id="two">texttextext</h1>
<br/>
<h1 class="main-text" id="three">texttextexttexttextext</h1>
所以这发生了,因为h1是一个块级元素。如果将display:inline-block
添加到CSS中,您将看到偏移量的差异。使用默认的display:block
元素将填充页面的宽度,即使您将其推过50%以上然后重置它。