I need to horizontally center the div
inner inside the outer based on this HTML and CSS code:
<div class="externo">
<div class="interno">
</div>
</div>
.interno {
background-color: green;
height: 20px;
width: 50%;
}
.externo {
background-color: red;
width: 200px;
padding: 20px;
}
JSFiddle: https://jsfiddle.net/fpvkcrkg/
Use automatic side margins.
You really only have to put them in their values
margin-left
andmargin-right
, but in your case, since you do not require a top and/or bottom margin, it would work that way, since according to the documentation, if you specify it that way, it would be the same as doing:That is, the upper and lower equals zero.
There are many ways to center elements with CSS , however one of the most popular in the last year is the use of Flexbox .
Using Flexbox the container does not need to have any specific properties to be placed in the space, however using Flexbox properties for the children you can do things unthinkable with traditional CSS.
To learn more about Flexbox I recommend you visit the following links:
If you're looking for a solution that doesn't include Flexbox then I recommend checking out Centering in CSS: A Complete Guide . This is the absolute guide on how to center elements using CSS no matter what browser you need to support.
Add a
margin:0 auto;
to the classinterno
in the CSS to achieve centering horizontally within the outer divYou can apply this CSS to the
div
inner:Of course, you don't have to set the width to 50%. Any width less than the
div
parent will work. Hemargin: 0 auto
is what the self-centered does.If you want to include IE8+, it might be better to use this instead:
It will make the inner element center horizontally, and it works without specifying a specific width.
Font
jsfiddle
You can use a flexbox on the
div
outer.By simply adding the last line, it is centered relative to its parent.
Another way is to use transform: translateX
Set the outer div to a position
relative
,absolute
orfixed
and it should have dimensions defined.In the inner div
position: absolute
andleft: 50%
, then applytransform: translateX(-50%)
.Tested on:
Note: Combined with translateY produces centering on both axes. You have to add to the inner div
top: 50%
.Simply add
display: inline-block
to the<div>
inside and center it by addingtext-align: center
to the<div>
outside.It would look like this:
The Fastest Is To Include The Label Within That Part Of Code, Without CSS Or Flex-Bos Or Na De Na...It Is Done That Simple:
The Fastest Is To Include The Label Within That Part Of Code, Without CSS Or Flex-Bos Or Na De Na...It Is Done That Simple: