最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I make an inline element take up space when empty? - Stack Overflow

programmeradmin0浏览0评论

I have an h1 and h3 tag that will erase itself and type, using theater.js. The problem is that when it erases itself to empty, the height of the div it's in get smaller, then snaps bigger when it has content again.

I want to make the h1 and h3 tag (or change the tag pletely) keep its height even while empty.

Any idea?

I have an h1 and h3 tag that will erase itself and type, using theater.js. The problem is that when it erases itself to empty, the height of the div it's in get smaller, then snaps bigger when it has content again.

I want to make the h1 and h3 tag (or change the tag pletely) keep its height even while empty.

Any idea?

Share edited Dec 2, 2024 at 9:35 VLAZ 29.2k9 gold badges63 silver badges84 bronze badges asked Mar 21, 2015 at 18:59 therealscifitherealscifi 3825 silver badges12 bronze badges 2
  • 1 Can you post some codes or something that you have tried please – AndrewL64 Commented Mar 21, 2015 at 19:00
  • 3 ...also headings are not inline elements...they are block level. – Paulie_D Commented Mar 21, 2015 at 19:03
Add a ment  | 

4 Answers 4

Reset to default 2

Just wrap your h2/h3 tag in a div with display: inline-block; like this:

<div class="header2"><h2>ABCD</h2></div>

and then add this to your css:

    .header2 {
      min-width: 100px;
      width: auto;
      min-height:45px;
      background-color:#333;
      color:#FFF;
      display:inline-block;
      padding:10px;
    }

Here's a jsfiddle of two h2 tags with the above properties: https://jsfiddle/AndrewL32/e0d8my79/21/

two possible solutions:

1) you can set min-height to the div

For example:

div{min-height:50px;}

2) or to set min-height of h2 and p1 tags

h1,p1 {

min-height:5px;

}

Demo for 2nd approach :

h1{
    background:yellow;
    min-height:5px;
}
<h1></h1>

Note: as paulie_D mentioned, h1 ,p and div are block level elements by default

You may use a pseudo element to force an empty space within the element and swip it away with text-indent

h1.fixed:before {
  content:' ';
  display:inline-block;
  width:1em;
}
h1 {
  background:lightgray;
  box-shadow:inset 0 0 0 1px;
  }
h1.fixed {
  text-indent:-0.8em; /* swip off the pseudo element */
  }
<h1 contenteditable="true"></h1>
<h1 class="fixed" contenteditable="true"></h1>

else, use the :empty pseudo-class

h1:empty:before {
  content:'|';
  }
<h1 contenteditable="true"></h1>

Instead of erasing the content of an H1 element, set it to &nbsp; . This is the entity that is rendered as a space. This should hide the element, but still take up the same vertical space as desired. Hopefully, it will not confuse screen readers (for blind users), either.

发布评论

评论列表(0)

  1. 暂无评论