Working with Display Block in CSS

CSSWeb DevelopmentFront End Technology

The CSS Display property with value block renders an element with parent’s full width available, it also forces a line break. An element with display as block renders as a <div> or <p> element.

Syntax

Following is the syntax of CSS display block −

Selector {
   display: block;
}

Example

Let’s see an example of CSS display block −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<title>CSS Display Block</title>
<style>
form {
   width:70%;
   margin: 0 auto;
   text-align: center;
}
* {
   padding: 2px;
   margin:5px;
}
input[type="button"] {
   border-radius: 10px;
}
em{
   background-color: #C303C3;
   color: #fff;
   display:block;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS-Display-Block</legend>
<label for="textSelect">Formatter: </label>
<input id="textSelect" type="text" placeholder="John Doe">
<input type="button" onclick="convertItalic()" value="Check">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var textSelect = document.getElementById("textSelect");
function convertItalic() {
   for(i=0; i<2; i++){
      var italicObject = document.createElement("EM");
      var italicText = document.createTextNode(textSelect.value);
      italicObject.appendChild(italicText);
      divDisplay.appendChild(italicObject);
   }
}
</script>
</body>
</html>

Output

This will produce the following output −

Before clicking ‘Check’ button −

After clicking ‘Check’ button −

Example

Let’s see another example of CSS Display block −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
#flex {
   display: flex;
}
#none {
   display: none;
}
.inline-block {
   display: inline-block;
   background-color: mintcream;
}
.grid {
   display: grid;
   background-color: cornflowerblue;
}
div {
   margin: 30px;
   padding: 5px;
   height: 10px;
   line-height: 5px;
   text-align: center;
   background-color: lightblue;
   border: 2px solid black;
}
div > div {
   background-color: lightpink;
   border: 2px solid green;
}
div > div > div {
   background-color: sandybrown;
   border: 2px solid darkred;
}
</style>
</head>
<body>
<div><span id="flex">heyyy</span>
<div><span id="none">heyyy</span>
<div>
<span class="inline-block">heyyy</span>
<span class="inline-block">heyyy</span>
<div>
<span class="grid">heyyy demo</span>
<span class="grid">heyyy demo</span>
</div>
</div>
</div>
</div>
</body>
</html>

Output

This will produce the following output −

raja
Published on 07-Jan-2020 11:59:08
Advertisements