2016년 1월 21일 목요일

DIV 상하 좌우 중앙정렬 하기


DIV를 가지고 놀다 보면 가운데 정렬이 필요한 경우가 있습니다.
좌우정렬은 그럭저럭 할만합니다만, 상하정렬은 약간의 노력이 필요합니다.

먼저, 큰 사각형 안에 작은 사각형을 넣어보겠습니다.


HTML

1
2
3
<div class="big-box">
    <div class="small-box"></div>
</div>


CSS

1
2
3
4
5
6
7
8
9
10
11
.big-box {
    height: 300px;
    width: 300px;
    background-color: #777777; 
}

.small-box {
    height: 100px;
    width: 100px;
    background-color: #aa0000; 
}


결과



위 코드를 이용해서 좌우정렬을 해보겠습니다.
다음과 같이 두 가지 방법이 있습니다.

1. margin 값으로 좌우정렬


CSS

1
2
3
4
5
6
.small-box {
    margin: 0 auto; /* 추가 */
    height: 100px;
    width: 100px;
    background-color: #aa0000; 
}


2. text-align 값으로 좌우정렬


CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
.big-box {
    text-align: center; /* 추가 */
    height: 300px;
    width: 300px;
    background-color: #777777; 
}

.small-box {
    display: inline-block; /* 추가 */
    height: 100px;
    width: 100px;
    background-color: #aa0000;
}
cs




어떤 방법을 사용하든 결과는 동일합니다.

이번에는 상하정렬을 해보겠습니다.
좌우정렬보다는 약간 까다롭습니다만, 약간의 팁만 알면 아주 쉽습니다.
상하정렬도 두 가지 방법이 있습니다.

1. margin 값으로 상하정렬


CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.big-box {
    text-align: center;
    height: 300px;
    width: 300px;
    background-color: #777777; 
}

.small-box {
    display: inline-block;
    margin-top: 100px; /* 추가 */
    height: 100px;
    width: 100px;
    background-color: #aa0000;
}


2. display: table-cell 로 상하정렬


CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.big-box {
    display: table-cell/* 추가 */
    vertical-align: middle/* 추가 */
    text-align: center;
    height: 300px;
    width: 300px;
    background-color: #777777; 
}

.small-box {
  display: inline-block;
    height: 100px;
    width: 100px;
    background-color: #aa0000;
}


결과



다음엔 좀더 나은 정보를 포스팅 하겠습니다.

2016년 1월 18일 월요일

DIV 가로 세로 비율을 일정하게 유지하기


화면 크기가 변해도 가로와 세로 비율이 일정하게 유지되는 DIV 를 만들수 있습니다.
JS 를 사용하지 않고 CSS 만으로도 가능합니다.


다음은 정사각형일 경우의 예제입니다.

HTML

1
2
3
<div class="proportion">
    <div class="content">정사각형</div>
</div>


CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.proportion {
    position: relative;
    width: 50%; /* 원하는 가로크기 */
} 
.proportion:before {
    content: "";
    display: block;
    padding-top: 100%; /* 1:1 비율 */
} 
.content { 
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}


padding-top 값에 따라 비율을 조절할 수도 있습니다.

가로:세로=1:1 비율은 100% 이고,
가로:세로=1:2 비율은 50% 입니다.

padding-top = 세로 / 가로 * 100


아래 링크에서 예제를 확인해 보실 수 있습니다.