Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

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.

like image 865
Nathan Ridley Avatar asked Sep 21 '10 09:09

Nathan Ridley


People also ask

How do you force a line break?

To do a line break in HTML, use the <br> tag. Simply place the tag wherever you want to force a line break. Since an HTML line break is an empty element, there's no closing tag. Below is an HTML file with a <p> and <br> element.

How do you automatically break lines in CSS?

word-wrap: break-word; is the current one. white-space: pre-wrap; is instead for something different! It preserves all whitespaces and linebreaks are ONLY done at \n (a linebreak in the source), <br> and as necessary to fill line boxes.

How do you break elements in CSS?

The break-after property extends the CSS2 page-break-after property. Using break-after , you can tell the browser to break the page, column, or region after the element the break-after property is applied to, or avoid the element to be split and span across two pages.


2 Answers

try this:

h3:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
like image 133
PeterWong Avatar answered Sep 20 '22 08:09

PeterWong


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.

like image 34
fredley Avatar answered Sep 22 '22 08:09

fredley