Search code examples
htmlcssline-breaks

Prescribing line break positions in CSS or HTML


The top of my website needs to have a center-justified 'message stripe' with the following important message: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem voluptates, obcaecati atque adipisci eligendi esse eum omnis quibusdam illum a eius quia facilis ex, deserunt, molestiae hic recusandae in unde!"

However, when the user makes the window narrower, I don't want unde! to fall onto a line by itself. Rather, I want everything after eum omnis to snap to the second line. When it gets even narrower, I want breaks after elit. and after illum a eius instead.

I'm imagining that this will call for @media queries, but I'm not sure how to go about it.

http://codepen.io/pgblu/pen/xGagpR

CSS:

#msgStripe {
  padding: 8px 0;
  background: #11dd44;
  line-height: 28px; 
  text-align: center;
}

HTML:

<div id="msgStripe">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem voluptates, obcaecati atque adipisci eligendi esse eum omnis quibusdam illum a eius quia facilis ex, deserunt, molestiae hic recusandae in unde!</div>

Solution

  • The key is to put line breaks (<br> tags) in the text, and then manipulate the display property of said <br> tags with media queries.

    For example, you can put <br> tags with classes like this:

    Lorem ipsum <br class="md" /> dolor sit <br class="sm" /> amet
    

    And use media queries to enable them

    br {display:none;/*Initially disable line breaks*/}
    
    @media(max-width:1200px) {
        br.md {display:inline;/*Enable br tags in screen width<=1200*/}
    }
    
    @media(max-width:767px) {
        br.sm {display:inline;/*Enable br tags in screen width<=767*/}
    }
    

    You will have to find the optimal position for placing <br> tags manually. (by emulating all media query breakpoints) But you get the idea.