패딩 / 여백이있는 CSS 100 % 높이
HTML / CSS를 사용하여 부모 요소의 100 % 인 너비 및 / 또는 높이를 가지면서도 적절한 패딩이나 여백이있는 요소를 어떻게 만들 수 있습니까?
"적절한"이란 내 부모 요소가 200px
크고 내가 지정 height = 100%
하면 모든면이 부모 요소의 중앙에 멋지게 중앙에 padding = 5px
있는 190px
높은 요소를 얻을 것으로 예상 할 수 있음을 의미합니다 border = 5px
.
이제 표준 상자 모델이 작동해야한다고 지정하는 방식이 아니라는 것을 알고 있습니다 (정확히 이유를 알고 싶지만 ...). 따라서 분명한 대답은 작동하지 않습니다.
#myDiv {
width: 100%
height: 100%;
padding: 5px;
}
그러나 임의의 크기의 부모에 대해이 효과를 안정적으로 생성하는 방법이 있어야한다고 생각합니다. 이 (겉보기에 간단 해 보이는) 작업을 수행하는 방법을 아는 사람이 있습니까?
아, 그리고 기록을 위해 나는 IE 호환성에별로 관심이 없으므로 (희망적으로) 일을 조금 더 쉽게 만들어야합니다.
편집 : 예제가 요청되었으므로 여기에 내가 생각할 수있는 가장 간단한 것이 있습니다.
<html style="height: 100%">
<body style="height: 100%">
<div style="background-color: black; height: 100%; padding: 25px"></div>
</body>
</html>
그런 다음 문제는 스크롤바를 요구할만큼 페이지가 커지지 않고 모든 가장자리에 25 픽셀 패딩이있는 블랙 박스를 표시하는 것입니다.
나는 " PRO HTML and CSS Design Patterns "를 읽고 이런 일을하는 방법을 배웠다 . 는 display:block
의 기본 표시 값입니다 div
,하지만 난 그것을 명시 적으로 만드는 것을 좋아합니다. 컨테이너는 올바른 유형이어야합니다. position
속성은 fixed
, relative
또는 absolute
입니다.
.stretchedToMargin {
display: block;
position:absolute;
height:auto;
bottom:0;
top:0;
left:0;
right:0;
margin-top:20px;
margin-bottom:20px;
margin-right:80px;
margin-left:80px;
background-color: green;
}
<div class="stretchedToMargin">
Hello, world
</div>
CSS3 에는 상자 모델이 너비 / 높이를 계산하는 방식을 변경하는 데 사용할 수 있는 새 속성 이 있습니다.이를 box-sizing이라고합니다.
이 속성을 "border-box"값으로 설정하면 패딩 또는 테두리를 추가 할 때 적용되는 요소가 늘어나지 않습니다. 너비가 100px이고 패딩이 10px 인 무언가를 정의하더라도 여전히 너비는 100px입니다.
box-sizing: border-box;
브라우저 지원은 여기를 참조하십시오 . IE7 이하에서는 작동하지 않지만 Dean Edward의 IE7.js 가 이에 대한 지원을 추가 한다고 생각 합니다. 즐겨 :)
해결책은 높이와 너비를 전혀 사용하지 않는 것입니다! 위, 왼쪽, 오른쪽, 아래를 사용하여 내부 상자를 부착 한 다음 여백을 추가합니다.
.box {margin:8px; position:absolute; top:0; left:0; right:0; bottom:0}
<div class="box" style="background:black">
<div class="box" style="background:green">
<div class="box" style="background:lightblue">
This will show three nested boxes. Try resizing browser to see they remain nested properly.
</div>
</div>
</div>
더 좋은 방법은 calc () 속성을 사용하는 것입니다. 따라서 귀하의 사례는 다음과 같습니다.
#myDiv {
width: calc(100% - 5px);
height: calc(100% - 5px);
padding: 5px;
}
Simple, clean, no workarounds. Just make sure you don't forget the space between the values and the operator (eg (100%-5px) that will break the syntax. Enjoy!
According the the w3c spec height refers to the height of the viewable area e.g. on a 1280x1024 pixel resolution monitor 100% height = 1024 pixels.
min-height refers to the total height of the page including content so on a page where the content is bigger than 1024px min-height:100% will stretch to include all of the content.
The other problem then is that padding and border are added to the height and width in most modern browsers except ie6(ie6 is actually quite logical but does not conform to the spec). This is called the box model. So if you specify
min-height: 100%;
padding: 5px;
It will actually give you 100% + 5px + 5px for the height. To get around this you need a wrapper container.
<style>
.FullHeight {
height: auto !important; /* ie 6 will ignore this */
height: 100%; /* ie 6 will use this instead of min-height */
min-height: 100%; /* ie 6 will ignore this */
}
.Padded {
padding: 5px;
}
</style>
<div class="FullHeight">
<div class="Padded">
Hello i am padded.
</div
</div>
1. Full height with padding
body {
margin: 0;
}
.container {
min-height: 100vh;
padding: 50px;
box-sizing: border-box;
background: silver;
}
<div class="container">Hello world.</div>
2. Full height with margin
body {
margin: 0;
}
.container {
min-height: calc(100vh - 100px);
margin: 50px;
background: silver;
}
<div class="container">Hello world.</div>
3. Full height with border
body {
margin: 0;
}
.container {
min-height: 100vh;
border: 50px solid pink;
box-sizing: border-box;
background: silver;
}
<div class="container">Hello world.</div>
This is one of the outright idiocies of CSS - I have yet to understand the reasoning (if someone knows, pls. explain).
100% means 100% of the container height - to which any margins, borders and padding are added. So it is effectively impossible to get a container which fills it's parent and which has a margin, border, or padding.
Note also, setting height is notoriously inconsistent between browsers, too.
Another thing I've learned since I posted this is that the percentage is relative the container's length, that is, it's width, making a percentage even more worthless for height.
Nowadays, the vh and vw viewport units are more useful, but still not especially useful for anything other than the top-level containers.
Another solution is to use display:table which has a different box model behaviour.
You can set a height and width to the parent and add padding without expanding it. The child has 100% height and width minus the paddings.
Another option would be to use box-sizing propperty. Only problem with both would be they dont work in IE7.
Another solution: You can use percentage units for margins as well as sizes. For example:
.fullWidthPlusMargin {
width: 98%;
margin: 1%;
}
The main issue here is that the margins will increase/decrease slightly with the size of the parent element. Presumably the functionality you would prefer is for the margins to stay constant and the child element to grow/shrink to fill changes in spacing. So, depending on how tight you need your display to be, that could be problematic. (I'd also go for a smaller margin, like 0.3%).
A solution with flexbox (working on IE11): (or view on jsfiddle)
<html>
<style>
html, body {
height: 100%; /* fix for IE11, not needed for chrome/ff */
margin: 0; /* CSS-reset for chrome */
}
</style>
<body style="display: flex;">
<div style="background-color: black; flex: 1; margin: 25px;"></div>
</body>
</html>
(The CSS-reset is not necessarily important for the actual problem.)
The important part is flex: 1
(In combination with display: flex
at the parent). Funnily enough, the most plausible explanation I know for how the Flex property works comes from a react-native documentation, so I refer to it anyway:
(...) flex: 1, which tells a component to fill all available space, shared evenly amongst other components with the same parent
Frank's example confused me a bit - it didn't work in my case because I didn't understand positioning well enough yet. It's important to note that the parent container element needs to have a non-static position (he mentioned this but I overlooked it, and it wasn't in his example).
Here's an example where the child - given padding and a border - uses absolute positioning to fill the parent 100%. The parent uses relative positioning in order to provide a point of reference for the child's position while remaining in the normal flow - the next element "more-content" is not affected:
#box {
position: relative;
height: 300px;
width: 600px;
}
#box p {
position: absolute;
border-style: dashed;
padding: 1em;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
<div id="box">
<p>100% height and width!</p>
</div>
<div id="more-content">
</div>
A useful link for quickly learning CSS positioning
Border around div, rather than page body margin
Another solution - I just wanted a simple border around the edge of my page, and I wanted 100% height when the content was smaller than that.
Border-box didn't work, and the fixed positioning seemed wrong for such a simple need.
I ended up adding a border to my container, instead of relying on the margin of the body of the page - it looks like this :
body, html {
height: 100%;
margin: 0;
}
.container {
width: 100%;
min-height: 100%;
border: 8px solid #564333;
}
<style type="text/css">
.stretchedToMargin {
position:absolute;
width:100%;
height:100%;
}
</style>
참고URL : https://stackoverflow.com/questions/485827/css-100-height-with-padding-margin
'developer tip' 카테고리의 다른 글
기존 Heroku 앱과 폴더를 연결하는 방법 (0) | 2020.09.29 |
---|---|
SQL Server의 함수와 저장 프로 시저 (0) | 2020.09.29 |
PHP에서 현재 날짜와 시간을 어떻게 얻습니까? (0) | 2020.09.29 |
JavaScript 콘솔의 색상 (0) | 2020.09.29 |
Java에서 싱글 톤 패턴을 구현하는 효율적인 방법은 무엇입니까? (0) | 2020.09.29 |