簡體   English   中英

如何在兩個標題之間繪制理想線?

[英]How do I draw an Ideal line between two headers?

我的HTML代碼具有以下結構:

h1 {
  text-align: center;
  font-size: 20pt;
  padding-bottom: 0;
}

h2 {
  text-align: center;
  font-size: 16pt;
}

<body>
  ...
  <div id="container">
    <h1>Title</h1>
    <h2>Sub</h2>
  </div>
  ...
</body>

我想在這兩個標題之間“畫”一條線,如下所示:

標題 - 子

它應該調整到標題的寬度:

更長的標題 - 子

標題 - 較長的副標題

(請原諒我的圖像編輯技巧)

有一種簡單的css方法嗎?

我認為最簡單,最靈活的方法是使用Flexbox 只需在h1h2元素中添加一些左右填充,這樣行總是比文本長一點。

 body { text-align: center; } .container { display: inline-flex; flex-direction: column; align-items: center; } h1 { font-size: 20px; padding: 0 10px; } h2 { font-size: 16px; padding: 0 10px; } .line { height: 3px; width: 100%; background: red; } 
 <div class="container"> <h1>Lorem ispum</h1> <span class="line"></span> <h2>Sub</h2> </div> <hr> <div class="container"> <h1>Ispum</h1> <span class="line"></span> <h2>Lorem ipsum dolor sit amet.</h2> </div> 

更新:您實際上可以使用.container上的偽元素執行此操作,但您需要指定順序,以便在h1元素之后顯示該行。

 body { text-align: center; } .container { display: inline-flex; flex-direction: column; align-items: center; } .container > h1 { order: 1; font-size: 20px; padding: 0 10px; } .container > h2 { padding: 0 10px; order: 3; } .container:before { content: ''; height: 3px; width: 100%; background: red; order: 2; } 
 <div class="container"> <h1>Lorem ispum</h1> <h2>Sub</h2> </div> <hr> <div class="container"> <h1>Ispum</h1> <h2>Lorem ipsum dolor sit amet.</h2> </div> 

您可以使用簡單的pseudo元素來處理此問題。 沒有html結構更改不支持交叉瀏覽器的CSS 我們需要在父項上使用table顯示,並在<h1>上創建一個新元素(帶有pseudo的邊框)。

看看這個例子:

 #container { display: table; margin: 0 auto; text-align: center; } h1:after { content:""; position: absolute; bottom: 0; left: 0; width: 100%; border-bottom: 3px solid red; } h1, h2 { margin: 5px 0; padding: 0 10px 5px; } h1 { position: relative; font-size: 20pt; } h2 { font-size: 16pt; } 
  <div id="container"> <h1>long long title</h1> <h2>Sub</h2> </div> <div id="container"> <h1>h1</h1> <h2>Sub</h2> </div> <div id="container"> <h1>h1</h1> <h2>long long subtitle</h2> </div> 

小提琴演示

試試這個:

#container {
  text-align: center;
}

h1 {
  border-bottom: 2px solid red;
  padding-bottom: 10px;
} 

/* h2 {
  padding-top: 0px;
  margin-top: 0px;
} */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM