One place for hosting & domains

      How To Use Float and Columns to Lay Out Content with CSS


      The author selected the Diversity in Tech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      There are many ways to work with layout on the web. The modern approaches tend to rely on CSS Grid and Flexbox properties to create many web layouts. However, before Grid and Flexbox existed, web developers relied heavily on the float and columns properties. The float property is used to allow inline elements to wrap around a floating element, and column sets parameters for arranging text in columns. Because these properties also have properties that neither Grid and Flexbox can replicate, learning this method of layout can add options and flexibility to a designer’s set of skills.

      In this tutorial you will work with the float and columns properties to create various layout styles and effects. You will use the float property to float a pull quote and an image and cause the content to wrap around those elements. Then you will use the columns property to adjust vertically long content to spread across the horizontal axis. Additionally, the concepts and methods of responsive web design will be covered as you work to apply the various styles.

      Prerequisites

      Setting Up the Initial HTML and CSS

      In this section you will set up the base HTML and CSS that will be used throughout the tutorial. You will use demo text content from Cupcake Ipsum and the font Comfortaa from Google Fonts.

      To begin, open the index.html file in your text editor. Then, add the following HTML to the file:

      index.html

      <!doctype html>
      <html>
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>Cupcake Layouts</title>
          <link rel="preconnect" href="https://fonts.gstatic.com"> 
          <link href="https://fonts.googleapis.com/css2?family=Comfortaa:wght@400;700&display=swap" rel="stylesheet">
          <link rel="stylesheet" href="styles.css" />
        </head>
        <body>
      
        </body>
      </html>
      

      There are a lot of page settings being defined inside the <head> element. The first <meta> element defines the characters set to use for the text. This way most special characters, such as an accent mark, will render without special HTML codes. The second <meta> element tells browsers (mobile browsers in particular) to treat the width of the device as the width of the content; otherwise the browser will simulate a 960 pixel desktop width. The <title> element provides the browser with the title of the page. The <link> elements load in the page styles: The first two load in the font, Comfortaa, from Google Fonts and the last loads the styles you will write for this tutorial.

      Next, the page will need content to style. You will use sample content from Cupcake Ipsum as filler copy to work with the styles. Throughout the tutorial, new code will be highlighted.

      Return to index.html in your text editor and add the highlighted HTML from the following code block:

      index.html

      <!doctype html>
      <html>
        <head>
          ...
        </head>
        <body>
          <article>
            <h1>Carrot Cake Pie Toffee Cheesecake</h1>
      
            <p>Gummi bears powder tootsie roll biscuit. Icing jelly-o tootsie roll powder pie dessert biscuit tiramisu. Jelly beans pudding lemon drops sesame snaps jujubes sesame snaps gummi bears tiramisu. Apple pie danish soufflé soufflé cupcake cookie donut. Cookie gummies powder dragée powder chocolate bar muffin jelly marshmallow. Cheesecake dessert chocolate bar chocolate cake gingerbread chocolate bar gingerbread wafer brownie. Bear claw cake sugar plum muffin candy canes tart cheesecake croissant candy canes. Gummi bears carrot cake sweet chocolate. Carrot cake cake sweet bear claw. Gummi bears chocolate pie croissant chocolate cake bear claw dragée.</p>
      
            <p>Tootsie roll cotton candy cake tiramisu pastry. Croissant oat cake ice cream dragée sweet roll soufflé marshmallow powder marzipan. Lemon drops cake bear claw cake sweet lollipop. Lollipop toffee liquorice apple pie gingerbread pastry tiramisu.</p>
      
            <h2>Jelly Beans Wafer Apple Pie Icing</h2>
      
            <p>Jelly cotton candy cake pastry carrot cake. Topping icing danish. Lollipop sesame snaps muffin bonbon icing. Lollipop chocolate bar jelly-o sweet roll. Topping bear claw sweet. Apple pie bonbon sweet lemon drops caramels topping pastry. Biscuit jelly tootsie roll cookie tiramisu cotton candy. Icing chocolate cake liquorice ice cream sesame snaps cupcake chocolate bar pudding gingerbread. Donut toffee ice cream chocolate biscuit.</p>
      
            <p>Carrot cake pie halvah toffee cheesecake chocolate cake gingerbread liquorice. Marshmallow danish candy fruitcake chocolate dessert. Bear claw chocolate bar sugar plum pudding cake cheesecake sweet. Marzipan lemon drops croissant gummies. Dessert carrot cake carrot cake cookie candy canes toffee. Biscuit bear claw candy canes muffin. Lollipop gummies tart danish tart sugar plum biscuit. Lemon drops muffin sugar plum sweet. Cotton candy pastry topping caramels gummies carrot cake marzipan tiramisu sesame snaps.</p>
      
            <p>Ice cream donut cookie. Donut icing cookie sweet roll topping cookie. Jelly beans marzipan jujubes jelly beans ice cream marzipan apple pie cake. Sweet croissant sweet roll carrot cake oat cake tiramisu ice cream wafer wafer. Candy canes jelly beans toffee danish. Liquorice donut macaroon caramels. Donut pie cupcake gummies. Icing jujubes pudding apple pie pastry muffin sweet roll ice cream chocolate bar. Liquorice icing sugar plum marshmallow icing.</p>
      
            <h2>Jelly Sugar Plum Chocolate Danish</h2>
      
            <p>Topping marzipan sesame snaps soufflé chupa chups cookie wafer cupcake. Jelly beans lollipop jelly beans. Chocolate cake lemon drops chupa chups candy icing tootsie roll danish liquorice. Gummies danish dragée apple pie jelly pie topping icing tootsie roll. </p>
      
            <p>Apple pie bear claw muffin tiramisu gummi bears cake muffin. Candy canes oat cake croissant cake liquorice topping halvah dessert cheesecake. Candy fruitcake muffin. Cookie oat cake gummies brownie dessert candy canes icing. Soufflé chocolate cake pastry toffee cheesecake macaroon liquorice gummi bears. Halvah tiramisu jujubes. Bear claw candy danish. Macaroon chocolate wafer soufflé biscuit. Bear claw biscuit sesame snaps biscuit liquorice sweet roll lollipop. Marshmallow bear claw dragée icing liquorice candy donut chupa chups. Halvah dessert bonbon cupcake cupcake sugar plum cotton candy toffee muffin. Bonbon gummi bears jujubes chupa chups oat cake candy canes.</p>
      
            <p>Gummies bonbon marzipan icing pudding. Jujubes croissant carrot cake. Pastry halvah pudding toffee. Lemon drops gingerbread chocolate apple pie jelly cheesecake.</p>
      
            <p>Fruitcake dessert chocolate cupcake carrot cake dessert candy canes chocolate soufflé. Cookie cupcake marzipan sesame snaps biscuit tart pie jelly-o. Halvah tiramisu gummies biscuit powder donut. Chocolate cake bear claw macaroon.</p>
      
            <h2>Gingerbread Macaroon Fruitcake</h2>
      
            <p>Jelly chocolate gummies cupcake liquorice chocolate. Sugar plum donut tiramisu muffin chupa chups. Cake caramels fruitcake jelly beans pudding I love pie lollipop jelly beans. Gummi bears cheesecake dragée I love fruitcake sesame snaps I love. Apple pie muffin donut. Fruitcake donut chocolate bar cotton candy topping candy macaroon I love. Fruitcake sesame snaps jelly-o. Tart wafer sugar plum I love apple pie biscuit. Pastry sesame snaps tart. Apple pie gingerbread chocolate candy canes.</p>
      
            <p>I love cake sweet roll toffee lemon drops bonbon sweet. Oat cake lemon drops candy canes topping macaroon.</p>
      
            <p>Sweet cotton candy danish. Lollipop bear claw pudding carrot cake. Gummi bears candy canes chocolate cake chupa chups. Sugar plum jelly cake cookie cheesecake croissant muffin carrot cake. Pudding I love liquorice jelly-o caramels I love sweet roll bonbon oat cake. Caramels gummi bears gingerbread.</p>
          </article>
        <body>
      </html>
      

      Save these additions to your index.html file then open it in your web browser. The content will use the browser default styles, as shown in the following image:

      Several paragraphs and headings of black serif text on a white background

      Create a file called styles.css in the same folder as index.html and open it in your text editor. This file will contain all the styles used throughout the tutorial. The first set of styles will apply a general aesthetic that you will build on later. Apply the CSS from the following code block to your styles.css file:

      styles.css

      body {
        font: 100%/1.5 Comfortaa, sans-serif;
        color: hsl(300, 100%, 10%);
        background-color: hsl(300, 100%, 98%);
      }
      
      article {
        width: 90%;
        max-width: 75ch;
        margin: 2rem auto;
      }
      
      h1 {
        font-size: 1.75rem;
        color: hsl(204, 100%, 29%);
        margin: 1em 0  0.5em;
      }
      
      h2 {
        font-size: 1.5rem;
        color: hsl(204, 100%, 29%);
        margin: 1em 0 0.5em;
      }
      

      These styles add a minimal set of styles, using a shorthand font property on the body selector to set a new default font family and line height between lines of the text. The styles set to the article selector make the container have a width slightly smaller than the full screen width, but keep that content centered with the margin property set to auto for the left and right values. The article also has a maximum with of 75ch, which means it only gets as wide as 75 zero characters of the set font-size value. Lastly, the h1 and h2 selectors set a new font-size, color, and margin for each.

      Save your changes to styles.css, then refresh index.html in your web browser. The following image shows how these new base styles will appear in the browser:

      Several paragraphs in a dark purple sans-serif font with larger headings in blue sans-serif font, all on a light purple background.

      In this section you set up the the base HTML and CSS needed to begin adding float and columns content. In the next section, you will create a block quote that floats, allowing content to wrap around it. You will also create a horizontal rule line that stops content from wrapping around the floating element.

      Floating Content

      Next you will add a <blockquote> element and apply a float property to cause the content to wrap around the floating content.

      To create the quote content, open index.html in your text editor. After the first <p> content block, add a <blockquote> opening and closing tag. Inside the <blockquote> tags, add a new <p> content block with a couple of sentences from Cupcake Ipsum. After the next <p> content block, but before the <h2> heading, add a horizontal rule using a self-closing <hr /> element. The highlighted HTML in the following code block indicates where and what to add to your file:

      index.html

      <!doctype html>
      <html>
        ...
        <body>
          <article>
            <h1>Carrot Cake Pie Toffee Cheesecake</h1>
      
            <p>Gummi bears powder tootsie roll biscuit. Icing jelly-o tootsie roll powder pie dessert biscuit tiramisu. Jelly beans pudding lemon drops sesame snaps jujubes sesame snaps gummi bears tiramisu. Apple pie danish soufflé soufflé cupcake cookie donut. Cookie gummies powder dragée powder chocolate bar muffin jelly marshmallow. Cheesecake dessert chocolate bar chocolate cake gingerbread chocolate bar gingerbread wafer brownie. Bear claw cake sugar plum muffin candy canes tart cheesecake croissant candy canes. Gummi bears carrot cake sweet chocolate. Carrot cake cake sweet bear claw. Gummi bears chocolate pie croissant chocolate cake bear claw dragée.</p>
      
            <blockquote>
              <p>Apple pie danish soufflé soufflé cupcake cookie donut. Cookie gummies powder dragée powder chocolate bar muffin jelly marshmallow.</p>
            </blockquote>
      
            <p>Tootsie roll cotton candy cake tiramisu pastry. Croissant oat cake ice cream dragée sweet roll soufflé marshmallow powder marzipan. Lemon drops cake bear claw cake sweet lollipop. Lollipop toffee liquorice apple pie gingerbread pastry tiramisu.</p>
      
            <hr />
      
            <h2>Jelly Beans Wafer Apple Pie Icing</h2>
            ...
          </article>
        </body>
      </html>
      

      Save these changes to your index.html file, then return to the web browser and refresh the page. The quote will inherit some styles from the initial set of CSS you wrote, but still have some browser default styles applied. The following image shows how the quote and horizontal rule will appear in the browser:

      Default indentation of a block quote in the browser with a rule line before the next heading text

      To start adding styles to the quote content, open styles.css in your text editor. First create a blockquote element selector and then add a padding of 1rem, a background-color property set to a dark purple with hsl(204, 100%, 15%), and lastly a color property set to a light yellow with hsl(24, 100%, 85%). Next, add a blockquote p combinator selector to increase the font-size of the content to 1.25rem and remove the default spacing by adding a margin property with a value of 0. The highlighted CSS in the following code block shows how this will be formatted in your text editor:

      styles.css

      ...
      h2 {
        font-size: 1.5rem;
        color: hsl(204, 100%, 29%);
        margin: 1em 0 0.5em;
      }
      
      blockquote {
        padding: 1rem;
        background-color: hsl(204, 100%, 15%);
        color: hsl(24, 100%, 85%);
      }
      
      blockquote p {
        font-size: 1.25rem;
        margin: 0;
      }
      

      Save your changes to styles.css, then reload index.html in the web browser. The blockquote styling will now have larger text with a darker background and light yellow text, as shown in the following image:

      Block quote in a dark blue background container with light yellow text

      Next, you will apply the float property to the blockquote. There are three value options for the float property: left, right, and none. This means the floating content will either go the left side of the wrapping content or the right side. If the content is already floating, you can use none to remove the floating feature. For the blockquote, you will set it to float to the left, so the paragraph below it wraps to the right.

      Return to styles.css in your text editor. In the blockquote element selector, add the float property with the value set to left, as highlighted in the following code block:

      styles.css

      ...
      blockquote {
        padding: 1rem;
        background-color: hsl(204, 100%, 15%);
        color: hsl(24, 100%, 85%);
        float: left;
      }
      ...
      

      At this point the blockquote is floating, but it will not cause any content to wrap because of an aspect of how floating is handled with the contents inside. A floating element still expands to the natural width of the content. This means that since the content inside the blockquote is so long, it will still take up the same amount of space as though it were not floating. To force a visual change, add a width property set to a value of 40% to the blockquote selector, as highlighted in the following code block:

      styles.css

      ...
      blockquote {
        padding: 1rem;
        background-color: hsl(204, 100%, 15%);
        color: hsl(24, 100%, 85%);
        float: left;
        width: 40%;
      }
      ...
      

      Save these changes to styles.css and then refresh index.html in your web browser. The width of the <blockquote> element is now constrained to 40% of the parent container width, which allows the paragraph below to pull up and wrap on the right. The following image shows how this will appear in your browser:

      Blockquote content on the left side with the following text content wrapping on the right side

      The last formatting adjustment that needs to be made to the blockquote is the spacing around the element.

      Return to styles.css in your text editor. Then go to blockquote element selector block and add a margin property with a value of 0 1rem 1rem 0. The highlighted line of CSS in the following code block shows how this is formatted:

      styles.css

      ...
      blockquote {
        padding: 1rem;
        background-color: hsl(204, 100%, 15%);
        color: hsl(24, 100%, 85%);
        float: left;
        width: 40%;
        margin: 0 1rem 1rem 0;
      }
      ...
      

      This margin value will set the right and bottom margin values to 1rem and the top and left values to 0, which provides space along the sides where the text wraps around the quote.

      Save your changes to styles.css, then return to index.html in your web browser and refresh. The following image shows how this will appear in the browser:

      Blockquote content on the left side with the following text content wrapping on the right side with less space around the block quote

      As it is now, the floating pull quote is large enough that it is causing the heading of the next section to wrap as well. This where the clear property is helpful to prevent this situation. The clear property, like float, has three property values to counteract the float property and stop content from wrapping. The values for clear are left, right, and a combination of the two with both. The element on which this property is placed will stop the wrapping from that point forward.

      To use the clear property, open styles.css in your text editor. You will use the <hr /> element to apply the clear property, so begin by creating an hr element selector. Then, to add an aesthetic style, add a border property with a value of 0.125 rem solid hsl(300, 50%, 90%) to create a thick border. Next, add a margin property set to 3rem 0 so there is extra space above and below the border. Finally, add the clear property and use the both value to stop the content from wrapping around the quote element. The highlighted CSS in the following code block shows how to format these styles:

      styles.css

      ...
      
      blockquote p {
        font-size: 1.25rem;
        margin: 0;
      }
      
      hr { 
        border: 0.125rem solid hsl(300, 50%, 90%);
        margin: 3rem 0;
        clear: both;
      }
      

      Save your changes to styles.css and return to the browser and refresh index.html. As shown in the following image, the <hr> element is no longer wrapping to the right of the quote. Instead, the rule line is below, extending the full width of the content. However, the distance between the quote and the <hr> uses the margin on the float and not the larger margin value of the <hr> element:

      Blockquote content on the left side with the following text content wrapping on the right side with a light purple rule line below

      In this section, you applied a float to a <blockquote>, which caused the other elements to wrap around it. You also added the margin to give white space around the quote, making the wrapping content more legible. In the next section, you will float an image when the screen size reaches a certain width using a media query.

      Floating Image at a Given Screen Width

      There are three requirements for effective responsive web design: flexible width, resizable images, and media queries. In this step, you will use all three of these to cause an image to float to the right at a specific screen width, and then at a larger screen size pull the image into the right side margin.

      To begin, load an image on to the page. Open index.html in your text editor, and add an <img /> element between the first two paragraphs following <h2>Jelly Beans Wafer Apple Pie Icing</h2>. Like the <hr /> element from the previous section, <img /> is a self-closing element; however, the <img /> requires a src attribute to where the image file is located that will be placed on the page. The highlighted HTML in the following code block shows how to set up the <img /> in your code:

      index.html

      <!doctype html>
      <html>
        ...
        <body>
          <article>
            ...
            <hr />
      
            <h2>Jelly Beans Wafer Apple Pie Icing</h2>
      
            <p>Jelly cotton candy cake pastry carrot cake. Topping icing danish. Lollipop sesame snaps muffin bonbon icing. Lollipop chocolate bar jelly-o sweet roll. Topping bear claw sweet. Apple pie bonbon sweet lemon drops caramels topping pastry. Biscuit jelly tootsie roll cookie tiramisu cotton candy. Icing chocolate cake liquorice ice cream sesame snaps cupcake chocolate bar pudding gingerbread. Donut toffee ice cream chocolate biscuit.</p>
      
            <img src="https://source.unsplash.com/-hM0-PSO3FY/450x300" alt="Icing lemon drops danish tiramisu soufflé" />
      
            <p>Carrot cake pie halvah toffee cheesecake chocolate cake gingerbread liquorice. Marshmallow danish candy fruitcake chocolate dessert. Bear claw chocolate bar sugar plum pudding cake cheesecake sweet. Marzipan lemon drops croissant gummies. Dessert carrot cake carrot cake cookie candy canes toffee. Biscuit bear claw candy canes muffin. Lollipop gummies tart danish tart sugar plum biscuit. Lemon drops muffin sugar plum sweet. Cotton candy pastry topping caramels gummies carrot cake marzipan tiramisu sesame snaps.</p>
            ...
          </article>
        </body>
      </html>
      

      For your image you are using a picture from the Unsplash image service to provide the src value. <img /> elements also need to have an alt attribute to provide description text. This description text can be used in many ways, but it is most important to provide contextual information for screen reader users.

      Save your changes to index.html and refresh the page in your browser. You will now have an image loading on the page between two of the paragraphs, as shown in the following image:

      Image between two paragraphs of text

      Images on web pages, by default, are displayed at their given pixel size. In the case of the image added to the HTML earlier, it has a size of 450 pixels wide and 300 pixels tall. When loaded on a mobile phone that has a screen size smaller than 450 pixels wide, then the image will go off screen and cause a horizontal scroll bar. To set images to resize to fit the space contained, you can use width: 100% on the img. However, this approach allows the image to get larger than its actual size, distorting the image as it grows, known as pixelization. Instead it is better to use max-width: 100%, which allows the image to shrink into more restrictive spaces, but not grow past its actual size.

      To create these resizing images, return to styles.css in your text editor. After the body element selector at the top of the document, add an img element selector. Inside the selector block add the max-width property with a value of 100%. The highlighted CSS in the following code block demonstrates how to set up the img selector:

      styles.css

      body {
        font: 100%/1.5 Comfortaa, sans-serif;
        color: hsl(300, 100%, 10%);
        background-color: hsl(300, 100%, 98%);
      }
      
      img {
        max-width: 100%;
      }
      
      article {
        width: 90%;
        max-width: 75ch;
        margin: 2rem auto;
      }
      ...
      

      Save these changes to styles.css and refresh index.html in your web browser. Take the browser window and decrease the width to something closer to a phone size. The image will shrink once the window width becomes smaller than the width of the image. The following image shows how this will look in the browser on a narrow width window:

      Image between two paragraphs of text on a small screen width device. The image is as wide as the text contnt.

      Now that you have a responsively scaling image, you will next move the image to float right when there is sufficient space. Changing styles at a certain window or screen width is accomplished with special at-rule conditions called media queries. A media query is defined by using the @media rule followed by a media condition in which to apply the styles it contains. In this case, you want the window size to be at least 640px. Since the end user can affect the meaning of a pixel, divide 640 by 16 to get a rem unit value of 40. After the query is defined it will have its own set of curly braces, inside which are the selectors that need to change at the specified screen width.

      Open the styles.css file in your text editor. Then create a media query set to a min-width of 40rem. Inside the query block, add an img element selector with a float property set to right. So the image doesn’t take up too much space in this view, set the max-width value to 50%. Lastly, use the margin property to add a margin to the left and bottom position of the image. The highlighted CSS in the following code block demonstrates how to add the media query and the associated styles:

      styles.css

      ...
      blockquote p {
        font-size: 1.25rem;
        margin: 0;
      }
      
      @media (min-width: 40rem) {
        img {
          float: right;
          max-width: 50%;
          margin: 0 0 1rem 1rem;
        }
      }
      ...
      

      Save your changes to styles.css, then return to the browser and refresh the page. Be sure to resize your browser from a small screen size out to a more common desktop browser window size. The image will now float to the right with the text content wrapping around to the left, as shown in the following image:

      Image floating on the right side, below the first paragraph, with the second paragraph wrapping to the left and beneath the image.

      The text now defines the layout and leaves lots of extra space on the right and left when on a larger desktop screen size. In this case, it can be both aesthetically and functionally helpful to pull the image into that extra space. This can be done with a negative margin value on the floating element.

      To create this effect, open styles.css in your text editor then add another media query for a min-width of 80rem, which is equivalent to 1280 pixels. Inside the query block, add an img element selector and return the max-width property to a value of 100%. Then add a margin property with the top and bottom positions set to 1rem and the left position set to 2rem. Set the right position to -40%. This value will pull the image into the white space on the right side of the content by 40% of the parent element’s width, not the img width. The highlighted CSS in the following code block demonstrates how to set this up:

      styles.css

      ...
      @media (min-width: 40rem) {
        img {
          float: right;
          max-width: 50%;
          margin: 0 0 1rem 1rem;
        }
      }
      
      @media (min-width: 80rem) {
        img {
          max-width: 100%;
          margin: 1rem -40% 1rem 2rem;
        }
      }
      ...
      

      Save these changes to styles.css then refresh index.html in the browser. You may need to expand the width of your window, but once it reaches a width of approximately 1280 pixels the image will pull to the right and the content will continue to wrap on the left. The following image shows how this will appear in the browser:

      Image floating on the right side and into the margins. The image is below the first paragraph, with the second and third paragraphs wrapping to the left and beneath the image.

      In this section you used a media query, a percentage width, and negative margin values to float an image and pull it into the white space of the layout. In the next section, you will begin to use the columns property to change some content from a single column to two columns at a given media query screen width.

      Column content

      When working with text content it can be helpful at times to adjust the layout so that the content is side by side, or even wrap from one column to the next. There are many ways to create columns with CSS, but only the columns property will divide the content of one element between different columns. In this section, you will use the columns property to create a two-column layout for the content to wrap. Then, you will use additional columns properties to create a dividing line between the columns and tell an element how to interact with the columns to force a column break.

      To begin, open index.html and wrap the two paragraphs after <h2>Jelly Sugar Plum Chocolate Danish</h2> in a <div> element with a class property of column. The highlighted HTML in the following code block shows how this will look in your file:

      index.html

      <!doctype html>
      <html>
        ...
        <body>
          <article>
            ...
            <h2>Jelly Sugar Plum Chocolate Danish</h2>
      
            <div class="column">
            <p>Topping marzipan sesame snaps soufflé chupa chups cookie wafer cupcake. Jelly beans lollipop jelly beans. Chocolate cake lemon drops chupa chups candy icing tootsie roll danish liquorice. Gummies danish dragée apple pie jelly pie topping icing tootsie roll. </p>
      
            <p>Apple pie bear claw muffin tiramisu gummi bears cake muffin. Candy canes oat cake croissant cake liquorice topping halvah dessert cheesecake. Candy fruitcake muffin. Cookie oat cake gummies brownie dessert candy canes icing. Soufflé chocolate cake pastry toffee cheesecake macaroon liquorice gummi bears. Halvah tiramisu jujubes. Bear claw candy danish. Macaroon chocolate wafer soufflé biscuit. Bear claw biscuit sesame snaps biscuit liquorice sweet roll lollipop. Marshmallow bear claw dragée icing liquorice candy donut chupa chups. Halvah dessert bonbon cupcake cupcake sugar plum cotton candy toffee muffin. Bonbon gummi bears jujubes chupa chups oat cake candy canes.</p>
      
            <p>Gummies bonbon marzipan icing pudding. Jujubes croissant carrot cake. Pastry halvah pudding toffee. Lemon drops gingerbread chocolate apple pie jelly cheesecake.</p>
      
            <p>Fruitcake dessert chocolate cupcake carrot cake dessert candy canes chocolate soufflé. Cookie cupcake marzipan sesame snaps biscuit tart pie jelly-o. Halvah tiramisu gummies biscuit powder donut. Chocolate cake bear claw macaroon.</p>
            </div>
      
            <h2>Gingerbread Macaroon Fruitcake</h2>
            ...
          </article>
        </body>
      </html>
      

      Save your changes to index.html, then return to styles.css in your text editor. When the content width is narrow, it is too small to be divided into columns. Instead, add a .column class selector within the min-width: 40rem media query. Then give the .column selector a columns property with a value of 2, as highlighted in the following code block:

      styles.css

      ...
      @media (min-width: 40rem) {
        img {
          float: right;
          max-width: 50%;
          margin: 0 0 1rem 1rem;
        }
      
        .column {
          columns: 2;
        }
      }
      
      @media (min-width: 80rem) {
        ...
      }
      

      Save the changes to styles.css and then refresh index.html in your web browser. The content of these two paragraphs will be separated into two columns with the first line of the second sentence at the bottom of the first column wrapping into the second column, as shown in the following image:

      Two columns of paragraph text flowing from one column on the left into the second column on the right.

      There are a handful of columns properties. The columns property itself is a shorthand combination of column-count and column-width. Should you need to define a specified width of the columns, it is important to know columns are always equal in size. There are also two companion properties to help with the visual presentation of the columns. The first is column-gap, which allows for specifying spacing between each column. The second property is called column-rule, which functions similarly to a border, but only draws a vertical line between the columns.

      To add a custom gap and rule, open styles.css in your text editor. In the .columns selector block, add the column-gap property with a value of 2rem. Next, add the column-rule property with a value of 2px solid hsl(300, 50%, 90%), which will create a vertical rule line between the columns using the same color as the <hr /> element earlier. The highlighted HTML in the following code block shows how this will look in your file:

      styles.css

      ...
      @media (min-width: 40rem) {
        img {
          float: right;
          max-width: 50%;
          margin: 0 0 1rem 1rem;
        }
      
        .column {
          columns: 2;
          column-gap: 2rem;
          column-rule: 2px solid hsl(300, 50%, 90%);
        }
      }
      
      @media (min-width: 80rem) {
        ...
      }
      

      Save the changes to styles.css and refresh index.html in your web browser. The space between the columns has increased and in the middle of the gap is now a solid vertical rule line, as shown in the following image:

      Two columns of text with a thin light purple line between the columns.

      Lastly, it is possible to apply properties to the elements inside the column to influence how they interact with the layout. The paragraph in the first column has more space on it than the text in the second column. This is because of how the column interacts with the margin property and the default margin value on <p> elements. The :first-child pseudo-class can be used to change the margin-top of the first <p> element inside the column. Next, there are a few properties to control how column elements interact with the column flow: break-inside, break-after, and break-before. You will use the break-inside property with the value avoid, which tells the browser to prevent breaking apart the contents of the <p> elements.

      Return to styles.css in your text editor to begin applying these new styles to the column content. Inside the media query, add a combinator selector consisting of .column p:first-child to scope the styles to the first <p> element inside the <div class="columns"> element. Then add the margin-top property set to a value of 0. Create a new combinator selector of .column p to apply these styles to all the <p> elements inside the <div class="columns"> element. Finally, add the break-inside property with a value of avoid to keep the columns from breaking apart the content. The highlighted CSS in the following code block demonstrates how to set this up:

      styles.css

      ...
      @media (min-width: 40rem) {
        ...
      
        .column {
          columns: 2;
          column-gap: 2rem;
          column-rule: 2px solid hsl(300, 50%, 90%);
        }
      
        .column p:first-child {
          margin-top: 0;
        }
      
        .column p {
          break-inside: avoid;
        }
      }
      ...
      

      Note: There are a some things to be aware of when it comes to using the break-inside, break-after, and break-before properties. While there is good browser support for these properties, the avoid value is the most well-supported, and the other values have mixed support. Additionally, the browsers that do support the avoid value will interpret when to break the column differently, causing varying layouts between browsers. Be cautious when using the property when visual parity is needed between browsers.

      Save your changes to styles.css and refresh the page in your web browser. The second paragraph has now been forced fully into the first column. This may make the first column larger than the second, but the vertical rule accommodates the change. The first paragraph also now aligns at the top with the second column. The following image shows how this will look in most browser:

      Two paragraphs of text, each in a different column, with a light purple vertical line between.

      In this section, you used the columns property to create two columns of flowing content. You used the column-gap property to provide more space and column-rule to create a dividing line between the columns. Finally, you used the break-inside property to force how the elements interacted with the column flow. In the last section you will apply the columns property to an ordered list and adjust its presentation with media queries.

      Column List

      In this last section, you apply what you have learned with columns, media queries, and negative margin values to style an ordered list. One of the advantages of the columns property comes in making long lists a much shorter height by dividing them into two or three columns.

      To begin, you will need to add an ordered list to your HTML. Open index.html in your text editor and add the highlighted HTML in the following code block just before the last paragraph in your file:

      index.html

      <!doctype html>
      <html>
        ...
        <body>
          <article>
            ...
            <h2>Gingerbread Macaroon Fruitcake</h2>
            <p>Jelly chocolate gummies cupcake liquorice chocolate. Sugar plum donut tiramisu muffin chupa chups. Cake caramels fruitcake jelly beans pudding I love pie lollipop jelly beans. Gummi bears cheesecake dragée I love fruitcake sesame snaps I love. Apple pie muffin donut. Fruitcake donut chocolate bar cotton candy topping candy macaroon I love. Fruitcake sesame snaps jelly-o. Tart wafer sugar plum I love apple pie biscuit. Pastry sesame snaps tart. Apple pie gingerbread chocolate candy canes.</p>
      
            <p>I love cake sweet roll toffee lemon drops bonbon sweet. Oat cake lemon drops candy canes topping macaroon.</p>
      
            <ol class="column-list">
              <li>Cookie I love gingerbread topping</li>
              <li>Carrot cake toffee I love croissant pudding</li>
              <li>Sesame snaps pastry jelly-o</li>
              <li>Fruitcake pastry dessert</li>
              <li>Lollipop gingerbread I love caramels</li>
              <li>Toffee</li>
              <li>Croissant pudding I love muffin</li>
              <li>Dessert jelly beans</li>
              <li>jelly beans</li>
              <li>Liquorice</li>
              <li>I love cotton candy</li>
              <li>Apple pie</li>
              <li>Lemon raspberry cheesecake</li>
              <li>muffin donut</li>
            </ol>
      
            <p>Sweet cotton candy danish. Lollipop bear claw pudding carrot cake. Gummi bears candy canes chocolate cake chupa chups. Sugar plum jelly cake cookie cheesecake croissant muffin carrot cake. Pudding I love liquorice jelly-o caramels I love sweet roll bonbon oat cake. Caramels gummi bears gingerbread.</p>
            ...
          </article>
        </body>
      </html>
      

      Save your changes to index.html and reload the page in the web browser. As shown in the following image, the ordered list is numbered 1–14 in a single column of content:

      An ordered list of content with sequential numbers preceding each list item

      Next, open up styles.css in your text editor and just before the first media query create an ol element selector. You will then add styles to help the list stand out visually with padding, a background-color, and finally a border. The highlighted CSS in the following code block demonstrates how to set this up and the values to use for the properties:

      styles.css

      ...
      blockquote p {
        font-size: 1.25rem;
        margin: 0;
      }
      
      ol {
        padding: 2rem;
        background-color: hsl(300, 60%, 95%);
        border: 0.25rem solid hsl(300, 50%, 90%);
      }
      
      @media (min-width: 40rem) {
        ...
      }
      ...
      

      Save the changes to styles.css then return to the web browser and refresh the page. The list will have a darker border and background color, as seen in the following image:

      Numerical ordered list of content within a container with a light purple border and an even lighter purple background.

      Next, return to styles.css in your text editor to add the column styles. Like the paragraphs in the previous section, these columns are most effective for larger screen sizes and better as a single column on smaller screens. Add an ol element selector in the min-width: 40rem media query. In the selector block add a columns property with a value of 2. Then, because the numbers of the ordered list are outside the container, the columns need extra space between them. To accomodate for this extra content, add a column-gap property set to 3rem. Lastly, at larger screen sizes it can be helpful to give more vertical space between elements. Add a margin property with the top and bottom positions set to 2rem and the left and right to 0. The highlighted CSS in the following code block demonstrates how to set this up:

      styles.css

      ...
      ol {
        padding: 2rem;
        background-color: hsl(300, 60%, 95%);
        border: 0.25rem solid hsl(300, 50%, 90%);
      }
      
      @media (min-width: 40rem) {
        ...
        ol {
          columns: 2;
          column-gap: 3rem;
          margin: 2rem 0;
        }
      }
      ...
      

      Save your changes to styles.css and return to the browser to refresh index.html. Be sure your browser window is at least 640 pixels wide. The list is now separated into two columns of similar length, as shown in the following image:

      Numerical ordered list of content within a boxed container split between two columns

      Next, the items in the ordered list could use more space between each. Return to styles.css in your text editor. After the ol selector in the (min-width: 40rem) media query, add a ol li combinator selector. In the selector block, add a margin-bottom property set to 1em, which sets it to be equal to the li element’s font-size. The highlighted CSS in the following code block shows where and how to add these styles:

      styles.css

      ...
      @media (min-width: 40rem) {
        ...
        ol {
          columns: 2;
          column-gap: 3rem;
          margin: 2rem 0;
        }
      
        ol li {
          margin-bottom: 1em;
        }
      }
      ...
      

      Save the changes to your index.html file, then return to the web browser and refresh the page. The spacing between each list item is now much larger, making the list more easily scanned by the reader. The following image shows how the list spacing looks in the browser:

      Numerical ordered list of content within a boxed container split between two columns with vertical space between each list item

      Lastly, return to styles.css in your text editor to apply a third column when there is enough screen space. Start by adding a ol element selector in the (min-width: 80rem) media query, then add a columns property set to 3. The gap between the columns will be inherited from the previous media query because you are using min-width queries, so that does not need to be redefined. However, three columns need extra space so the columns are not too narrow. In order to give the list extra space, add a margin property that keeps the top and bottom positions set to 2rem, but changes the left and right positions to a negative value of -5rem. The highlighted CSS in the following code block demonstrates how to set this up:

      styles.css

      ...
      @media (min-width: 40rem) {
        ...
      }
      
      ...
      
      @media (min-width: 80rem) {
        img {
          float: right;
          width: 80%;
          margin: 1rem -40% 1rem 2rem;
        }
      
        ol {
          columns: 3;
          margin: 2rem -5rem;
        }
      }
      ...
      

      Save your changes to styles.css, then reload index.html in the web browser. Like the floating image earlier, this negative value will pull the sides of the list into the extra side space of the page. This creates a visual prominence that brings attention to the list. The following image shows how this looks in the browser:

      Numerical ordered list of content within a boxed container split between three columns and extending outside the layout into the space on the right and left.

      In this last section you combined everything you learned from the previous sections. You used media queries, columns, and negative margins to create a striking ordered list style that can be used to help lists have a more interesting presentation.

      Conclusion

      There are many ways to lay out content with CSS, and each property has its own special strength. In this tutorial, you used the float property to create elements that cause the other content to wrap around it. You also used the columns property to create content that flows from one column to the next. Additionally, you put into practice some of the principles of effective responsive design using media queries and flexible widths. As you approach layout solutions in your web projects, it is important to be aware of the various ways to accomplish the task. Both the float and columns properties provide a way to create something unique and help provide good visual design.

      If you would like to read more CSS tutorials, try out the other tutorials in the How To Style HTML with CSS series.



      Source link

      How To Lay Out Text with CSS


      The author selected the Diversity in Tech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      The way text is presented on a web page determines how legible the content is and how willing the reader is to read the content. Web typesetting, the art of laying out text, is about controlling the content to present the reader with a pleasant and efficient reading experience.

      This tutorial will teach you how to use the CSS properties that are most effective at laying out text content. You will use properties like line-height, letter-spacing, and text-transform with demo content to optimize for reading and define a content hierarchy by giving headings prominence. These concepts and approaches will help you better present content on your websites.

      Prerequisites

      Setting Up the HTML and CSS Files

      In this section you will set up the HTML content that you will style throughout the tutorial. The purpose of the HTML in this tutorial is to provide various elements and situations to style. You will also create your CSS file and set a base style.

      To begin, open index.html in your text editor and add the following HTML to the file:

      index.html

      <!doctype html>
      <html>
          <head>
          </head>
          <body>
          </body>
      </html>
      

      Next, in the <head> tag, you will add a meta tag for the character set for this page, a title element for the title of the page, a meta tag defining how the page should be handled on mobile devices, and the CSS files to load:

      index.html

      <!doctype html>
      <html>
          <head>
              <meta charset="UTF-8" />
              <title>Text Layout</title>
              <meta name="viewport" content="width=device-width" />
              <link rel="preconnect" href="https://fonts.gstatic.com" />
              <link href="https://fonts.googleapis.com/css2?family=Public+Sans:ital,wght@0,400;0,700;1,400;1,700&amp;family=Quicksand:wght@700&amp;display=swap" rel="stylesheet" />
              <link href="https://www.digitalocean.com/community/tutorials/styles.css" rel="stylesheet" />
          </head>
          <body>
          </body>
      </html>
      

      Notice that the CSS files include a couple of fonts from Google Fonts and the styles.css file you will create later in this section. If you’d like to learn more about how to use Google Fonts, check out How To Style Text Elements with Font, Size, and Color in CSS.

      Now you will set up the HTML content contained within the page’s <body> tag. This content will be contained in an <article>, which will have an <h1> element, a couple each of <h2> and <h3> elements, and several <p> elements throughout. You will fill these tags with text content from the Cupcake Ipsum filler text generator. This filler content will provide all that is needed to apply visual styles for this tutorial.

      Apply the HTML to your index.html, as shown in the highlighted sections of the following code block:

      index.html

      <!doctype html>
      <html>
          <head>
              ...
          </head>
          <body>
              <article>
                  <h1>Sugar plum chupa chups chocolate bar cupcake donut</h1>
                  <h2>Tootsie roll oat cake macaroon</h2>
                  <p>Jujubes brownie candy. Dessert tootsie roll pie gummi bears danish cotton candy. Sugar plum <strong>I love fruitcake pastry</strong>. Jelly-o gummi bears muffin gummi bears marzipan cheesecake donut gingerbread I love. Cupcake wafer cake.</p>
                  <p>Cupcake donut topping <em><strong>chupa chups halvah</strong></em> chupa chups. Macaroon tootsie roll cupcake caramels chocolate fruitcake gingerbread jelly-o. Tiramisu I love marshmallow jelly-o I love jelly beans candy gummi bears.</p>
                  <h2>Jelly beans tiramisu pastry danish donut</h2>
                  <h3>Lemon drops pastry marshmallow</h3>
                  <p>I love marshmallow candy. <em>Sesame snaps</em> muffin danish. Chocolate cake cookie jelly-o tiramisu halvah brownie halvah chocolate chocolate cake. Jelly-o caramels jujubes bonbon cupcake danish tootsie roll chocolate bar. Macaroon I love muffin candy canes sweet roll I love. I love bonbon marshmallow croissant ice cream I love gummi bears.</p>
                  <p>Pie apple pie I love jujubes biscuit I love. Chocolate cake pastry tiramisu <strong>soufflé powder caramels</strong> I love ice cream. Dragée liquorice toffee jelly jelly beans. Sesame snaps candy canes soufflé. Biscuit donut bear claw jujubes halvah pastry macaroon lemon drops. Tootsie roll dragée cookie candy soufflé dragée cupcake liquorice.</p>
                  <h3>Apple pie pudding topping</h3>
                  <p>Powder dragée sesame snaps candy canes jelly-o. Halvah gingerbread cheesecake wafer. <strong><em>Wafer tootsie roll</em></strong> I love I love. Cake toffee I love. Cotton candy cotton candy jelly beans I love bonbon toffee. Chupa chups chupa chups caramels ice cream halvah candy chocolate cake. Marshmallow carrot cake jelly beans.</p>
                  <p>Chocolate cake sweet roll pudding chocolate cake fruitcake bear claw.</p>
              </article>
          </body>
      </html>
      

      Save all these additions to your index.html file and then open the file in your web browser. As you write your styles, have the index.html file loaded in your browser to check how your styles are applied to the content:

      Content in a serif font with black text on a white background.

      Next, create a file in the same directory as index.html called styles.css and open the new file in your text editor.

      There are two font families that you will load from Google fonts. The first font will be the default font for the page, as it will be used by all content on the page.

      Create a body type selector and add a font-family property with the font stack 'Public Sans', sans-serif to set this as the new default font:

      styles.css

      body {
          font-family: 'Public Sans', sans-serif;
      }
      

      This applies the font to the body element. All the content in this example will inherit that font, without needing to be declared individually. The font name is Public Sans, and it will have a fallback font that uses the browser’s default sans-serif font. Fonts should always have a fallback font using a comma separated list called a font stack. Fallback fonts provide a readable option if the custom font doesn’t load or lacks a special character.

      Next, the heading elements, h1, h2, and h3, will get a special font for the rest of the page called Quicksand. Create a group selector consisting of the three headers h1, h2, h3 and apply the same font stack setup as the body with Quicksand:

      styles.css

      body {
          font-family: 'Public Sans', sans-serif;
      }
      
      h1, h2, h3 {
          font-family: 'Quicksand', sans-serif;
      }
      

      Save your changes to styles.css and return to your browser to reload index.html. The custom font will now load, as shown in the following image:

      Content with black text on a white background with heading text in a rounded sans serif font and the paragraphs in sans serif font.

      For the last part of setting up your files, return to your styles.css file in the text editor. Create singular type selectors for the h1, h2, h3, and p elements to define a font-size for each. Use the rem unit for value, setting the h1 to 2.5rem, the h2 to 1.875rem, the h3 to 1.5, and the p to 1.25rem:

      styles.css

      ...
      h1, h2, h3 {
          font-family: 'Quicksand', sans-serif;
      }
      
      h1 {
          font-size: 2.5rem; /* 40px */
      }
      
      h2 {
          font-size: 1.875rem; /* 30px */
      }
      
      h3 {
          font-size: 1.5rem; /* 24px */
      }
      
      p {
          font-size: 1.25rem; /* 20px */
      }
      

      The code block includes a comment that indicates what each rem value will return as a px unit. The rem unit gives the user more control over adjusting the font-size to a preferable ratio than the px value allows. For more on these units, read through How To Use Common Units in CSS.

      Save your changes to styles.css and return to your browser to reload the index.html file. The text font sizes will adjust to look similar to the following image:

      Content with black text on a white background with heading text in a rounded sans serif font and the paragraphs in sans serif font with various sized text.

      In this section you set up your HTML content in index.html and created your styles.css file. You applied the Google Font typefaces to the CSS globally on the body element and specifically to the h1, h2, and h3 elements. You also set the font-size values for all the text elements on the page. In the next section you will use the width property to create more readable line lengths.

      Improve Line Lengths Using width and max-width

      In this section, you will use the width and max-width properties to set an appropriate line length for the text.

      An often overlooked aspect of web typography is how long a line of text is presented. For both users in need of accessibility assistance and those without, the length of a line contributes significantly to the effort needed to read the text. The longer a line of text is the more likely the reader will have difficulty keeping track of the text. Shorter lines of text help the reader navigate and scan the content.

      Open styles.css in your text editor and write an article type selector to apply a width of 90% and add a margin property with a value of 0 auto. This combination will make sure the content is set to be 90% of the screen’s width, and the auto value in the margin will keep the content block in the middle of the page:

      styles.css

      ...
      article {
          margin: 0 auto;
          width: 90%;
      }
      

      Save these changes to styles.css and reload index.html in your browser. The text will be centered, but the lines of text will be very long. See the following image for how this will appear in your browser:

      Text content in black taking up 90% of the width, with equal spacing on either side.

      The ideal line length is between 45 and 75 characters, as explained by Clarissa Peterson in her talk on Responsive Typography. Longer than 75 characters and the reader can begin to lose track of what line they are reading. On the other hand, shorter than 45 characters and the readers eyes can become fatigued from the constant moving from line to line.

      Setting a width based on a character count is possible with a unit called the character unit, represented by ch in code. The ch unit is determined by the size of the zero character (0) in the font. Since the ideal line length is between 45–75 characters, you can set a max-width value in that range, and the article element will stop growing once it has reached that size.

      Return to the styles.css file in your text editor and, after the width property in the article type selector, add a max-width property and give it a value of 70ch:

      styles.css

      ...
      article {
          margin: 0 auto;
          width: 90%;
          max-width: 70ch;
      }
      

      This means that the maximum width the element is allowed to grow is the width of 70 zero characters of the font used in that space, which is the font set on the body element.

      Save these changes to your styles.css file and reload index.html in your browser. You will find the content centered in the page at a maximum width of approximately 70 characters long. Try resizing the width of your browser to watch the article container transition from a 90% width to its maximum width, as shown in the following animation:

      Animation showing a browser window with content growing in width with the window until the content reaches a maximum width.

      Note: Chris Coyier, of CSS Tricks, created a handy bookmarklet tool that will highlight the range of characters between 45 and 75 to help find the best width to set your content.

      In this section you learned that accessibility and legibility share a common ground with the line length of text content. You used the width property with the max-width property to set a size limiting the text length to 45–75 characters using the ch unit. In the next section, you will use the line-height property to set the appropriate spacing between lines of text.

      Using the line-height Property to Help Readability

      You will use the line-height property in this section to expand and contract the space between the lines of text. You may find that headings typically have less space between lines and that paragraph text tends to have more space. The goal for this spacing is to make the content easier to read. Similar to the width of lines of text, if the lines are too close together, the reader may be distracted by the line above or below. On the other hand, if the text is too far apart, the reader’s eyes can grow tired of jumping over the space between lines and find the text much harder to scan.

      Open your styles.css file in your text editor and go to the body selector. Like the font-family, you will use line-height to set a default distance between lines for the whole document. Add the line-height property and give a value of 1.5. This value is a measurement of the distance between baselines, the line on which the bottom of text rests:

      styles.css

      body {
          font-family: 'Public Sans', sans-serif;
          line-height: 1.5;
      }
      ...
      

      The default for line-height is tied to the keyword value of normal, which is equal to 1.2 of the font size. This means if the font-size is 16px, then the line-height when set to normal is approximately 19.2px. This is a good median value; however, paragraph text usually needs a bit more space, while a heading sometimes needs a bit less.

      Next, go to the group selector targeting h1, h2, h3 and set a line-height value to 1.15. This will bring the text between lines a bit closer together, and can help the presentation of long heading titles. Add the highlighted line in the following code block:

      styles.css

      ...
      h1, h2, h3 {
          font-family: 'Quicksand', sans-serif;
          line-height: 1.15;
      }
      ...
      

      Save your changes to styles.css and return to the browser to reload index.html. You will find the length of the content expand as more space is placed between lines of text. See the following image for how this appears in the browser:

      Text content in black on white with headlines closer together vertically and paragraph lines of text further apart.

      The value for the line-height property can accept fixed unit values, as well as pixel (px) or rem, but it is better to leave no unit as the default behavior is to multiply the value by the font-size.

      You used the line-height property in this section to make the content on the page more legible and easier to scan for the reader. In the next section, you will use the margin properties to set a defined amount of space between types of content as defined in the HTML.

      Using the margin Properties for Spacing

      In this section, you will use the margin property along with the adjacent sibling selector to apply different vertical spacing between the text elements. Where the line-height property gives control between lines of text in an element, margin can be used to adjust the spacing between content elements.

      To begin, return to styles.css in your text editor and find the h3 selector. In this situation, you will add spacing to the element to have more space above the text and less space beneath. This will cause it to be farther from the content above and closer to the content below.

      Add a margin property with a value of 2em 0 0.5em. This will apply spacing that is relative to the font-size value, meaning the top margin will be double the font-size at 48px and the bottom will be half the font-size at 12px:

      styles.css

      ...
      h3 {
          font-size: 1.5rem; /* 24px */
          margin: 2em 0 0.5em;
      }
      ...
      

      Since the margin works on the outside of the element, each element’s margin properties will overlap. This means that even though the h3 margin on the bottom side is equivalent to 12px, the <p> element’s margin is larger and therefore defines the space between the <h3> and <p>. You can solve this problem by using the adjacent sibling combinator, which is defined by a plus sign (+) between two selectors, with styles applied to the latter in the sequence.

      Create a new selector in styles.css in your text editor using the adjacent sibling combinator as h3 + p, then within the selector block add a margin-top property with a value of 0:

      styles.css

      ...
      h3 {
          font-size: 1.5rem; /* 24px */
          margin: 2em 0 0.5em;
      }
      
      h3 + p {
          margin-top: 0;
      }
      ...
      

      The way the adjacent sibling combinator works, this means that when the browser has an <h3> element and immediately following it is a <p> element, then these styles are applied to only that <p> element. Other <p> elements are unaffected.

      Save your changes to styles.css and load index.html in your browser. As shown in the following image, the space above the <h3> elements is now much larger and the space between the <h3> and first <p> after it is much closer.

      Black text content with a large spacing between two headers.

      In this section, you used the margin property to apply different spacing between the elements of the page. With the adjacent sibling selector, you set up conditionals that would apply a greater spacing amount if the <h3> element was preceded by a <p> element. In the next section, you will use the text-align property to adjust the placement of the text on a line.

      Using text-align for Effective Content Presentation

      You will now use the text-align property to change where the text is placed on a line. The property has four values: left, right, center, and justify. The default value for this property depends on the browser’s language setting. For languages that read from left to right, left is the default, while languages that read right to left have a default of right. The center property places the text in the center of the line of text and leaves an equal amount of blank space on either side of the line of text. Lastly, the justify value spreads the words out to the edges of the container, leaving visually inconsistent spaces between words.

      Open styles.css in your text editor and find the h3 type selector. Add a text-align property with a value of center as shown in the highlighted portion of the following code block:

      styles.css

      ...
      h3 {
          font-size: 1.5rem; /* 24px */
          margin: 2em 0 0.5em;
          text-align: center;
      }
      ...
      

      Save your changes to styles.css and reload the index.html file in your browser. The content of the two h3 level headings are now centered above their respective sections. See the following image for how this appears in the browser:

      Black sans serif text centered to the container.

      It is best to keep the text-align property set to the default, as this is best for the user and their settings. However, changing the alignment value can help distinguish some text better or provide a better aesthetic.

      You used text-align in this section to center text content within its container. You also learned how and when to use the other values available to the text-align property. In the next section, you will use the text-transform and letter-spacing properties to create visual personality while still keeping the text readable and maintaining efficient hierarchy.

      Using letter-spacing and text-transform

      Next, you will use the text-transform property and the letter-spacing property to adjust how the text of a headline appears. The text-transform property controls how text capitalization is formatted, providing options to change the text to uppercase, lowercase, or capitalize, which capitalizes the first letter of each word. The letter-spacing property is the value of space between each character. Together these two properties can create an aesthetic that is legible and stands out.

      Begin with the text-transform property by opening styles.css in your text editor and go to the h1 type selector. Since this heading is the title of the whole article, it makes sense to have title-case formatting.

      Add a text-transform property with a value of capitalize. This value will capitalize the first letter of each word, regardless of if it is capitalized in the HTML:

      styles.css

      ...
      h1 {
          font-size: 2.5rem; /* 40px */
          text-transform: capitalize;
      }
      ...
      

      Save this addition to your styles.css file, then open index.html in your browser. The heading copy now has the first letter of each word capitalized, as shown in the following image.

      Large black text in a rounded sans serif font, with the first letter of each word capitalized.

      Next, return to the styles.css file in your text editor and find the h3 type selector. This time you will set up the h3 style to be all uppercase letters in each word by adding a text-transform property with a value of uppercase. Add the highlighted line for the following code block to your styles.css file:

      styles.css

      ...
      h3 {
          font-size: 1.5rem; /* 24px */
          margin: 2em 0 0.5em;
          text-align: center;
          text-transform: uppercase;
      }
      ...
      

      After you have made this change, save styles.css and then refresh index.html in your browser. The h3 content will now be all uppercase, regardless of how it is written in the HTML. See the following image for how this appears in the browser:

      Horizontally centered content in a black rounded sans serif font, all uppercase.

      Note: When using CSS to apply uppercase styling to content, it can affect how screen readers interpret the content. For example, with Voice Over on macOS, a three-letter word that is set to uppercase by CSS will be read as an acronym instead of as a word. When using this styling approach, it is helpful to apply an aria-label attribute to the HTML element with how the content should be read.

      Now that the text is all uppercase, visually the text feels a little bunched together for the aesthetic of the design. Next, use the letter-spacing property to add 0.125em spacing between each character. See the highlighted code in the following code block:

      styles.css

      ...
      h3 {
          font-size: 1.5rem; /* 24px */
          margin: 2em 0 0.5em;
          text-align: center;
          text-transform: uppercase;
          letter-spacing: 0.125em;
      }
      ...
      

      Using the em unit on a letter-spacing property allows the spacing between characters to be proportional to the font-size. The 0.125em keeps the spacing at one-eighth the height of the font.

      Save your changes to styles.css and reload index.html in your browser to render the changes to the h3 content. See what this will look like in the following image:

      Horizontally centered content in a black rounded sans serif font, all uppercase, with extra space between each characer.

      In this section, you used the text-transform property to change the styles for the <h1> element to capitalize the first letter of each word. You also used the text-transform and letter-spacing properties to change the <h3> element to have all uppercase words with the characters spread apart. In the last section, you will use the font property to condense multiple properties into one.

      Using the font Shorthand

      In this last section, you will use the font property to condense multiple properties into a single property. The font property can be useful when defining several text-related values globally, and placed at a high level in the cascade. Be aware that using the font shorthand will overwrite the individual properties it contains.

      To start, return to your styles.css file in your text editor and go to the body selector. Here the font-family and line-height properties can be condensed into the font shorthand property. However, the font shorthand requires that both a font-size and font-family value are present. This means adding a font-size value in addition to the line-height and font-family values. See the highlighted section of the following code block for how to write this out:

      styles.css

      body {
          font: 1em/1.5 'Public Sans', sans-serif;
      }
      ...
      

      Notice that there is a forward slash (/) between the font-size value of 1em and the line-height value of 1.5. This is the only way to set a line-height value with the font shorthand property, and it must come after the font-size value. The font-size value is set to 1em since that is the least disruptive value and carries over the default font-size of the document regardless of its value. Additionally, the font property shorthand accepts values for the font-stretch, font-style,font-variant, and font-weight properties.

      Be sure to save your changes to styles.css in your text editor. Reload the index.html in your browser and verify there are no visual changes. Since a shorthand property combines existing properties into a single property, there are no changes to the styles.

      You used the font property in this last section of the tutorial to combine several properties into one, condensing the size of your CSS. This property, though very useful, must be used with consideration as it can require redefining properties due to its broad coverage.

      Conclusion

      Readable text layout can mark the difference between an effective and ineffective design. Laying out text is a subjective balance of providing sufficient space between text lines, words, and blocks to present the content in an unobtrusive manner. When working with text, poor layout can prevent readers from understanding the content. With these properties and their uses in mind, you will make well-read content.

      If you would like to read more CSS tutorials, try out the other tutorials in the How To Style HTML with CSS series.



      Source link