Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you center a div element in react w/out external css file

How do I center a div element in react with using an external css file. I tried using bootstrap classes and inline styles that other people posted but none of those worked. I was wondering how you guys would implement this without an external css file.

like image 931
user3088470 Avatar asked Aug 29 '15 03:08

user3088470


People also ask

How do I center a div in Reactjs?

js, set its display property to flex and its alignItems and justifyContent properties to center . The div's content will be horizontally and vertically centered.


2 Answers

If you don't have to support old browsers, you may look into Flexbox.

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Try something like this:

<div style={{display: 'flex', justifyContent: 'center'}}>   <div>centered content</div> </div> 
like image 149
Jeff Fairley Avatar answered Oct 05 '22 21:10

Jeff Fairley


Offsets: The first uses Bootstrap's own offset classes so it requires no change in markup and no extra CSS. The key is to set an offset equal to half of the remaining size of the row. So for example, a column of size 6 would be centered by adding an offset of 3, that's (12-6)/2.

In markup this would look like:

<div class="row">     <div class="col-md-6 col-md-offset-3"></div> </div> 

margin-auto: You can center any column size by using the margin: 0 auto; technique, you just need to take care of the floating that is added by Bootstrap's grid system. I recommend defining a custom CSS class like the following:

.col-centered{     float: none;     margin: 0 auto; } 

Now you can add it to any column size at any screen size and it will work seamlessly with Bootstrap's responsive layout :

<div class="row">     <div class="col-lg-1 col-centered"></div> </div> 
like image 27
Atul Nagpal Avatar answered Oct 05 '22 20:10

Atul Nagpal