2017-04-08 59 views

回答

1

您可以使用CSS Flexbox的一个干净和简单的解决方案。

main {       /* 1 */ 
 
    display: flex; 
 
    justify-content: center; 
 
} 
 

 
h2 { 
 
    display: inline-flex;   /* 2 */ 
 
    flex-direction: column; 
 
    align-items: center; 
 
    margin: 0; 
 
} 
 

 
h2>span { 
 
    margin-left: auto;   /* 3 */ 
 
}
<main> 
 
    <h2> 
 
    WebsiteName<span>.com</span> 
 
    </h2> 
 
</main>

注:

  1. 块级容器;给予h2空间水平居中。
  2. 使h2成为内联级容器,因此该框只与内容一样宽。这允许第一行和第二行对齐。
  3. 将第二行对齐到右侧。

替代方法,使用绝对定位,基于意见反馈:

h2 { 
 
    display: inline-flex; 
 
    flex-direction: column; 
 
    align-items: center; 
 
    margin: 0; 
 
    position: absolute; 
 
    left: 50%; 
 
    transform: translateX(-50%); 
 
} 
 

 
h2>span { 
 
    margin-left: auto; 
 
}
<h2> 
 
    WebsiteName<span>.com</span> 
 
</h2>

+0

这个伟大的工程!除了我有一个问题,我希望我的h2元素的位置是绝对的。因为如果它没有设置为绝对,那么它会让我的网站布局混乱。 –

+0

是否有可能使.com更接近WebsiteName? –

+0

是的。你可以调整'line-height'或者使用一个负的'margin':https://jsfiddle.net/kcdfdao3/2/ –

0

您可以尝试的标签或定义类的float属性。

0

通过添加以下语法:

.class_name tag_name 
相关问题