Reputation: 477
I am quite new to html and CSS. And came across a big issue recently.
I have 2 divisions in another division. Both of those divs have few buttons etc, and are next to each other - inline. But, when I try to minimize my chrome window, 2nd div moves under 1st, which is great. But, they both are aligned to left of the screen. How could I make them stick to center?
Since I don't know how to explain better, here are some images.
How the divisions look like:
What happens when I resize browser:
What I want to happen with resize:
I sincerely hope someone can offer some type of suggestions.
Many thanks!
Upvotes: 2
Views: 429
Reputation: 2236
I am assuming from your question that you are interested in horizontal-centering and not vertical centering as well.
I am also quite new to HTML / CSS, but over the past few weeks I have found the flex facility to be quite useful. Using https://css-tricks.com/snippets/css/a-guide-to-flexbox/ has proven to be most helpful.
The following HTML and CSS files illustrate how flex can be used to achieve the desired effect.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta name = "viewport"
content = "width = device-width, initial-scale = 1.0"
>
<link href = "CSS/Example.css"
rel = "stylesheet"
type = "text/css"
>
</head>
<body>
<div id = "entire-page"
class = "empty-cell"
>
<div id = "inner-div-1"
class = "empty-cell"
>
</div>
<div id = "inner-div-2"
class = "empty-cell"
>
</div>
</div>
</body>
</html>
CSS
html,
*
{
border : 0;
box-sizing : border-box;
margin : 0;
padding : 0;
}
.empty-cell
{
min-height : 1px;
}
#entire-page
{
align-content : flex-start;
background-color : blue;
display : flex;
flex-wrap : wrap;
float : left;
height : 100vh;
justify-content : center;
width : 100%;
}
#inner-div-1
{
background-color : red;
display : block;
float : left;
height : 200px;
width : 400px;
}
#inner-div-2
{
background-color : yellow;
display : block;
float : left;
height : 200px;
width : 400px;
}
I used flex-wrap : wrap so that the second div would wrap onto the next line when there was no longer enough room for both on one line.
I used justify-content : center to horizontally center the contents of the flex-box (namely, the two inner-div's).
I used align-content : flex-start to keep the two inner-div's together when displaying them vertically, otherwise they would have been evenly spaced across the entire flex-box.
If you have any questions about this answer, then please feel free to ask them.
Upvotes: 1
Reputation: 371261
Try this:
Give the outer div
(the parent container) a text-align: center
.
Since the child divs are inline
, the text-align
property on the parent can control their alignment.
Upvotes: 1
Reputation: 1086
You can center inline elements by adding text-align: center; to the container element.
.container {
text-align: center;
}
and if you don't want the text within the elements centered then...
.container * {
text-align: left;
}
Upvotes: 1