CSS 만 사용하는 줄 바꿈 (예 : <br>)


84

추가 html 태그를 추가하지 않고 순수한 CSS에서 줄 바꿈을 만들 수 <br>있습니까? <h4>요소 뒤에서 줄 바꿈을 원 하지만 이전 은 원하지 않습니다.

HTML

<li>
  Text, text, text, text, text. <h4>Sub header</h4>
  Text, text, text, text, text.
</li>

CSS

h4 {
  display: inline;
}

I have found many questions like this, but always with answers like "use display: block;", which I can't do, when the <h4> must stay on the same line.


Why is this element an h4? Why do you use it in a place like this?
toniedzwiedz

Our of curiosity, what is the reason you don't want to use <br/>?
Philip Kirkbride

1
The reason: I have an awfull lot of list elements. And I was also wondering if an elegant solution exists. It is usually not nice to use br tags between elements (and I see the header as an element of its own)
Steeven

@Tom, this is a simplified example. I have som text and headers in each list element.
Steeven

답변:


134

It works like this:

h4 {
    display:inline;
}
h4:after {
    content:"\a";
    white-space: pre;
}

Example: http://jsfiddle.net/Bb2d7/

The trick comes from here: https://stackoverflow.com/a/66000/509752 (to have more explanation)


10
\a means line break, character U+000A, and white-space: pre tells browsers to treat it as a line break in rendering.
Jukka K. Korpela

Okay, thanks @JukkaK.Korpela. Then why isn't it rendered as a line break in the first place? Though this solution is simple, it still would override other white-space commands.
Steeven

3
@Steeven, it only overrides the initial value for white-space on the :after pseudo-element, which contains just the line break. And it is needed because in HTML, by default, a line break in element content is equivalent to a space and does not cause a line break in the rendered document.
Jukka K. Korpela

3
@Alshten, thanks, makes sense & totally weirds me out at the same time.
sonjz

Would have never thought of this. It's a shame one can't insert HTML though!
Lodewijk

7

Try

h4{ display:block;}

in your css

http://jsfiddle.net/ZrJP6/


1
plus some judicious use of margin-bottom should get you there.
Jeremy Holovacs

4
But if I understand well, the h4 has to be on the same line as the text before. With display:block, there's a line break before the h4.
adriantoine

What? margin-bottom will put the h4 at the same line as the preceding text?
Steeven

!! This is not a working solution : your line after will be "display : none" in browsers like Safari !!
Gregdebrick

5

You can use ::after to create a 0px-height block after the <h4>, which effectively moves anything after the <h4> to the next line:

h4 {
  display: inline;
}
h4::after {
  content: "";
  display: block;
}
<ul>
  <li>
    Text, text, text, text, text. <h4>Sub header</h4>
    Text, text, text, text, text.
  </li>
</ul>

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.