.center {
margin: auto;
width: 50%;
border: 3px solid green;
padding: 10px;
}
Note: Center aligning has no effect if the width property is not set (or set to 100%).
Example
.center {
text-align: center;
border: 3px solid green;
}
Tip: For more examples on how to align text, see the CSS Text chapter.
Example
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 40%;
}
Example
.right {
position: absolute;
right: 0px;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}
Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.
.right {
float: right;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}
Then we can add the clearfix hack to the containing element to fix this problem:
Example
.clearfix::after {
content: "";
clear: both;
display: table;
}
Example
.center {
padding: 70px 0;
border: 3px solid green;
}
To center both vertically and horizontally, use padding and text-align: center:
Example
.center {
padding: 70px 0;
border: 3px solid green;
text-align: center;
}
Example
.center {
line-height: 200px;
height: 200px;
border: 3px solid green;
text-align: center;
}
/* If the text has multiple lines, add the following: */
.center p {
line-height: 1.5;
display: inline-block;
vertical-align: middle;
}
Example
.center {
height: 200px;
position: relative;
border: 3px solid green;
}
.center p {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Tip: You will learn more about the transform property in our 2D Transforms Chapter.
Example
.center {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid green;
}
Tip: You will learn more about Flexbox in our CSS Flexbox Chapter.
<style>
.intro {
width: 200px;
____ : ____ ;
}
</style>
<body>
<div class="intro">
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Phasellus imperdiet, nulla et dictum interdum,
nisi lorem egestas odio,
vitae scelerisque enim ligula venenatis dolor.
</div>
</body>
<style>
.intro {
width: 200px;
margin : auto ;
}
</style>
<body>
<div class="intro">
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Phasellus imperdiet, nulla et dictum interdum,
nisi lorem egestas odio,
vitae scelerisque enim ligula venenatis dolor.
</div>
</body>
10 videos|41 docs|23 tests
|
|
Explore Courses for Class 6 exam
|