Hướng dẫn căn giữa css w3school
▲ ▼ Show
◀ ► Center elementshorizontally and verticallyCenter Align ElementsTo horizontally center a block element (like ), use
margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container. The element will then take up the specified width, and the remaining space will be split equally between the two margins: This div element is centered. Example .center { Try it Yourself » Note: Center aligning has no effect if the Center Align TextTo just center the
text inside an element, use This text is centered. Tip: For more examples on how to align text, see the CSS Text chapter. Center an ImageTo center an image, set left and right margin to Example img { Try it Yourself » Left and Right Align - Using positionOne method for aligning elements is to use In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since. Example .right
{ Try it Yourself » Note: Absolute positioned elements are removed from the normal flow, and can overlap elements. Left and Right Align - Using floatAnother method for aligning elements is to
use the Example .right { Try it Yourself » The clearfix HackNote: If an element is taller than the element containing it, and it is floated, it will overflow outside of its container. You can use the "clearfix hack" to fix this (see example below). Without ClearfixWith ClearfixThen we can add the clearfix hack to the containing element to fix this problem: Example .clearfix::after { Try it Yourself » Center Vertically - Using paddingThere are many ways to center an element vertically in CSS. A simple solution is to use top and bottom I am vertically centered. To center both vertically and horizontally, use I am vertically and horizontally centered. Example
.center { Try it Yourself » Center Vertically - Using line-heightAnother trick is to use the I am vertically and horizontally centered. Example .center { /* If the text has multiple lines, add the following: */ Try it Yourself » Center Vertically - Using position & transformIf I am vertically and horizontally centered. Example .center { .center p { Try it Yourself » Tip: You will learn more about the transform property in our 2D Transforms Chapter. Center Vertically - Using FlexboxYou can also use flexbox to center things. Just note that flexbox is not supported in IE10 and earlier versions: I am vertically and horizontally centered. Example .center { Try it Yourself » Tip: You will learn more about Flexbox in our CSS Flexbox Chapter. |