Remark
I am absolutely sure that these questions have been asked before, but I just cannot seem to find it. Whether I am searching with the wrong keywords or just not understanding what is going on I do not know. Honestly, I am quite embarrassed to even be asking this question since it seems absolutely trivial. It has been quite some time that I worked with CSS, so I am quite sure that this is something really basic.
Questions
- Why does a child div that is smaller (e.g. with a fixed with) have a right margin that extends up until the border of the parent element?
- Why am I not able to restrict said margin with specifying
right-margin
? - What is the best way to resolve this?
Example
<div>
<div style="height: 50px; width: 50px; background-color: black" />
</div>
As you can see in the inspector, the most nested div
actually has a margin that extends all the way to the parents border.
Setting the right-margin
does not affect this.
Any help would be deeply appreciated, please do feel free to redirect me to other questions if this has already been asked!
CodePudding user response:
This is because by default div is a block(display: block)
which as you probably already know forces a container to take 100% width
For its child to be position at the start it needs right margin which in this case is calc(100% - 50px)
, this pushes element to left to place it at the same offsetX as its parent.
You cannot restrict it unless you change display: block
of parent to flex
, grid
or whatever it is, because this is not your thing.
Well theoritically you can restrict it but you have to add margin-left
to child instead of trying to restrict margin-right
.
CodePudding user response:
just add display:inline-block
on style code.
<div>
<div style="height: 50px; width: 50px; background-color: black; display: inline-block" />
</div>
CodePudding user response:
Looks like the browser's own space. You can try reset css.
Example:
html {
box-sizing: border-box;
font-size: 16px;
}
*, *:before, *:after {
box-sizing: inherit;
}
body, h1, h2, h3, h4, h5, h6, p, ol, ul {
margin: 0;
padding: 0;
font-weight: normal;
}
ol, ul {
list-style: none;
}
img {
max-width: 100%;
height: auto;
}