[CSS] Các cách để căn giữa element trong css

Đăng bởi: Admin | Lượt xem: 2039 | Chuyên mục: CSS3

Hôm nay chúng ta sẽ cùng tìm hiểu các cách để căn giữa element trong css.


1.Using Flexbox

HTML

<div class="container">
<img src="http://lorempixel.com/400/200" />
</div>

CSS

html, body, .container {
  height: 100%;
}

.container {
  display: flex;
  justify-content: center; /* horizontal center */
  border: 1px solid gold;
  width: 50%;
  height: 50%;
  background-color: gray;
}

img {
  align-self: center; /* vertical center */
}

2.CSS transform

HTML:

    <div class="container">
      <div class="element"></div>
    </div>

CSS:

.container {
  position: relative;
  background-color: gainsboro;
  width: 30%;
  height: 30%;
}
.element {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 50%;
  height: 50%;
  background-color: gold;
}

3.margin: 0 auto;

HTML:

<div class="containerDiv">
    <div id="centeredDiv"></div>
</div>

CSS:

.containerDiv {
  width: 50%;
  background-color: gold;
}

#centeredDiv {
  margin: 0 auto;
  width: 200px;
  height: 100px;
  background-color: green;
}

4.Using position: absolute

HTML:

<div class="parent">
    <img class="center" src="http://lorempixel.com/400/200/" />
</div>

CSS:

.parent {
  background-color: green;
  position: relative;
  width: 30%;
  height: 30%;
}
.center {
  position: absolute;
  margin: auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: yellow;
}

5.Horizontal and Vertical centering using table layout

HTML:

<div class="wrapper">
      <div class="parent">
        <div class="child">

        </div>
      </div>
    </div>

CSS:

.wrapper {
  display: table;
  vertical-align: center;
  width: 200px;
  height: 200px;
  background-color: #9e9e9e;
}

.parent {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

.child {
  display: inline-block;
  vertical-align: middle;
  text-align: center;
  width: 100px;
  height: 100px;
  background-color: teal;
}

Đó là các cách căn chỉnh center mà tôi biết hy vọng có thể giúp mọi người trong công việc font-end. Happy coding!

vncoder logo

Theo dõi VnCoder trên Facebook, để cập nhật những bài viết, tin tức và khoá học mới nhất!



Khóa học liên quan

Khóa học: CSS3

Học Bootstrap 4
Số bài học:
Lượt xem: 16411
Đăng bởi: Admin
Chuyên mục: CSS3

Học CSS3
Số bài học:
Lượt xem: 14480
Đăng bởi: Admin
Chuyên mục: CSS3