I have so far been trying to create a basic website layout shown in this picture.
https://imgur.com/a/JhURder
It includes a grey background, with a centered div inside with a white background. With centered an image to the left and text etc to the right.
I am a large advocate for twitter bootstrap, so far I have implemented this. (React style)
<div class="container-fluid" style={{
'background-color' : 'rgb(224,225,226)',
'height' : '40vh'
}}>
<div class="row">
<div class="col-1 text-center"> Test </div>
<div class="col-10 text-center" style={{
'height' : '30vh',
'background-color' : 'rgb(255,255,255)',
'margin-top' : '5vh'
}}>
centered
</div>
<div class="col-1 text-center">test</div>
</div>
</div>
So far it half ways. But honestly I kind of gave us because it’s turned into a nested mess. With website development I always know their is a bigger way, so I come here for people to roast my attempt so far and could give me in a proper way of reaching my goal.
3
Answers
Try setting the css
margin: 0 auto
in your inner div that you want to center.Here’s some ideas of how you can achieve it.
https://codepen.io/Warisara-L/pen/wOMxwR
Have a good day sir 🙂
With FlexBox
With
display: flex;
you can specify the propertiesjustify-content
andalign-items
tocenter
in order to center child elements both horizontally and vertically.When a
display: flex
element is a row (flex-direction: row;
)justify-content
will handle horizontal positioning whilealign-items
handles vertical positioning. Whenflex-direction
is set tocolumn
,justify-content
andalign-items
meanings are swapped.Example:
With CSS Grid
You can utilize the property
place-items
to center the children of a grid. You should be aware, however, thatplace-items
is not currently supported on all browsers.Example:
Margin auto
Sometimes you can utilize the
auto
value for themargin
property to push an element towards the center.Be sure to check out this post that explains what is needed for
margin: auto;
to work.Example:
Absolute positioning with a transform
You can position an item in the center of the screen by setting the
position
property toabsolute
(this will take it out of the normal document flow). Then, you can use the propertiesleft
andtop
to move the element down and to the right50%
.Once it’s pushed
50%
we need to move it back half the width/height of the element, we can do that with atranslate
inside the propertytransform
.Example:
Disclaimer:
This is not advised for elements that are a part of your normal document flow as they will most likely overlap other elements. It’s great for modals though.