In CSS, what is a better way of forcing a line break after an element than making it a block element?

送分小仙女□ 提交于 2020-01-02 00:56:10

问题


I have an H3 heading that I'd like to style as having a particular background color, but without having the element's background take up the full width of the parent element. Seeing as H3 is by default a block element, my style would need to change the element to an inline-block element, or just an inline inline element like so:

h3 {
    background-color: #333;
    color: white;
    display: inline-block;
}

This will work fine, but only if it is immediately followed by a block element. I do not want to change the markup just to cater for this style, so I was wondering if there is a way to cause any adjacent element, irrespective of how it displays, to start on the next line?

Assume I can use CSS3.


回答1:


try this:

h3:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}



回答2:


display:block;
width:auto;

This will make the width as small as possible (not filling the whole parent element) and make other elements appear below.




回答3:


How often does it happen that the element after the <h3> is an inline element? (Usually after a header there should be like a <p>, <ul> or other block elements, although this totally depends on your html. Is it predictable? Is it an option to just turn every element that directly follows a <h3> into a block element?

h3 ~ * { display: block }

The only other way I know to have a block-element not take up all the space is floating it, but this leaves another problem.




回答4:


I come across this all the time in my code, usually for div's that are inline-block'ed. The best way I've seen is to force a new line is to wrap your code in an additional div. Your original html gets the formatting you expected and the div wrapper forces a new line.

Assuming this is your h3 styling,

h3 {
  display: inline-block;
}

Then just wrap it in a div.

<div>
   <h3>My heading</h3>
</div>



回答5:


I've had to do something similar with inline nav items that need breaking at certain points. Does this work?

h3:after {
  content: "\A ";
  line-height: 0;
  white-space: pre;
  display:inline-block;
}

I seem to remember IE7 having an issue with it.




回答6:


If you don't need to center h3, this may help:

h3 {
  background-color: #333;
  color: white;
  display: inline-block;
  float: left;
  clear: left;
}


来源:https://stackoverflow.com/questions/3759132/in-css-what-is-a-better-way-of-forcing-a-line-break-after-an-element-than-makin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!