+ 11
The art of centering elements in html
When I started learning html/css I found that it was a nightmare to center html elements. Is there a general way to center any type of html element with css that is valid for all versions of html, browsers and that is responsible? If not possible, is there the definitive guide to center each type of element in some page ?
13 Antworten
+ 11
Use can also use flex properties
https://code.sololearn.com/Wo1QS7H8I8tu/?ref=app
ref : https://www.w3schools.com/css/css3_flexbox.asp
+ 10
::sk:: I ask this question because recently I develop a html page with a centered element. Depending on browser firefox/ie in my computer or browser in mobile screen, its center behaviour changed. I guess that there is a general solution but only valid for some browsers and for last css versions
+ 7
In HTML you have <center> tag which is deprecated. In CSS you change the position of elements individually.
Example:
button {
position: absolute;
left: 45℅ or 50℅;
}
That is how I usually center non text elements in HTML and it works flawlessly
+ 7
That too. Well, depending on the width of the elements that have to go in the center, different percentages can be used. Or pixels if you are more comfortable with them. I just gave a random example.
+ 7
If you want the elements to be centered in mobile and laptop, you can do the following:
Example:
button {
position: absolute;
left: 45℅;
}
And then add media query for mobile phones:
@media screen and (max-width: 400px){
button {
position: absolute;
left: 30℅;
}
}
Again, this is just a random example. The exact percentages or pixels is something you have to figure out by yourself, depending on the content you want to center.
You can also adjust the viewport in the meta tags in the HTML pages. Hope this helps.
+ 6
Of course, you have to take into account that in different devices the position of the elements will be different.
+ 4
Inline stuff within block elements can be centered with the align attribute in general.
As for the rest it always depends :)
Which is not an answer but rather seconding your elaborate claim of that being a nightmare...
+ 4
Vasilis Karapas right... moreover, it depends on width of button elements' possible contents...
+ 4
I always use this to center elements in css:
#element {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
}
here's a working example:
https://code.sololearn.com/Wsb5m6RPraYa/?ref=app
+ 4
it is easy by flex property:
justify-content:center;
align-items:center;
+ 2
use this code:
container ( for example:body)
element (for example: div.cicle)
html:
<body>
<div class="circle"></div>
</body>
css:
body{
background-color:black;
display:flex;
justify-content:center;
align-items:center;
}
.circle{
width:50px;
height:50px;
border-radius:50%;
background-color:gold;
}
+ 1
try also http://flexboxfroggy.com/