Block-level Elements and Block Boxes in CSS


Block-level elements have their CSS display property set to either ‘block’, ‘list-item’, or ‘table’ and these elements force a line break above and below themselves. Block-level boxes are generated by each block-level element which is a part of the positioning scheme as well as contains child boxes.

Block container boxes contain either block-level boxes and follow block formatting context or contain inline-level boxes and follow inline formatting context. Block boxes is a term used if block-level boxes are also block containers.

Anonymous block boxes are those boxes over which developer has no control. If an inline box contains a block box and the inline content around the block box is enclosed in an anonymous block box.

Set the Form

First, set the form and its width −

form {
   width:70%;
   margin: 0 auto;
   text-align: center;
}

Style the Child

Set the height and width for the child −

.child{
   height: 40px;
   width: 100%;
   color: white;
   border: 4px solid black;
}

The :nth-of-type(n) Selector

For the elements, we have used the :nth-of-type(n) selector. It matches every element that is the nth child, of the same tag of its parent −

<div id="container">Color Orange
   <div class="child"></div>Color Red
   <div class="child"></div>Color Violet
   <div class="child"></div>
 </div>

The nth Child

The above is set with :nth-of-type(n) selector −

.child:nth-of-type(1){
   background-color: #FF8A00;
}
.child:nth-of-type(2){
   background-color: #F44336;
}
.child:nth-of-type(3){
   background-color: #C303C3;
}

Example

Let’s see an example to implement Block-level Elements and Block Boxes −

<!DOCTYPE html>
<html>
<head>
   <title>CSS Block-level Elements and Block Boxes</title>
   <style>
      form {
         width:70%;
         margin: 0 auto;
         text-align: center;
      }
      * {
         padding: 2px;
         box-sizing: border-box;
         /*margin:5px;*/
      }
      .child{
         height: 40px;
         width: 100%;
         color: white;
         border: 4px solid black;
      }
      .child:nth-of-type(1){
         background-color: #FF8A00;
      }
      .child:nth-of-type(2){
         background-color: #F44336;
      }
      .child:nth-of-type(3){
         background-color: #C303C3;
      }
   </style>
</head>
<body>
   <form>
      <fieldset>
      <legend>CSS Block-level Elements and Block Boxes</legend>
      <div id="container">Color Orange
         <div class="child"></div>Color Red
         <div class="child"></div>Color Violet
         <div class="child"></div>
      </div><br>
   </form>
</body>
</html>

Updated on: 27-Oct-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements