-1

I have a very simple layout that I am trying to achieve in CSS, but I am not having any luck. All I want to do is (horizontally) center a div that contains a link. The size of the div should be based on the size of its content.

I have tried a bunch of combinations of auto margins, text alignments, and display types, but can't seem to figure it out (I am a CSS noob). I have cooked up a very simple case (and the best I can do)

HTML:

<body>

    <div class="myDiv">
        <a href="google.com">google.com</a>
    </div>

</body>

CSS:

.myDiv
{
    background:lightblue;
    text-align:center;
    margin-left:auto;
    margin-right:auto;
}

.myDiv a
{
     text-decoration:none;
}

I have made a Fiddle as well. Is this type of layout possible without complicated HTML/CSS /hacks?

A.R.
  • 15,405
  • 19
  • 77
  • 123
  • change your magins to be margin: 0 40%; that works great for the demo. – Decker W Brower Nov 13 '13 at 17:08
  • 3
    auto margins only work when a specific value for the div's width is given. You could just apply your styles to the anchor tag itself. – Novocaine Nov 13 '13 at 17:09
  • No, this is not a duplicate, please read the question. – A.R. Nov 13 '13 at 17:25
  • 1
    This *is* a duplicate, about a hundred times over. What you're seeing below is well-trodden ground. – isherwood Nov 13 '13 at 17:31
  • @isherwood You are correct, this is a duplicate question, and I have also voted to close it. I am completely new to CSS so I got confused and thought the cases were different for some reason. – A.R. Nov 14 '13 at 13:25

3 Answers3

1

You just can do this:

.myDiv
  {
   display:table;
   margin:auto;
  }

View the demo http://jsfiddle.net/VvL6M/9/

DaniP
  • 37,813
  • 8
  • 65
  • 74
  • 1
    Aah, good ol' table to the rescue! – A.R. Nov 13 '13 at 17:29
  • 1
    It works, but I'd call this a last resort. There's usually no need to make divs act like tables. – isherwood Nov 13 '13 at 17:32
  • In anyway to do this you still need to change the display for the div ..... and this avoid the style for any parent like display:inline-block needs – DaniP Nov 13 '13 at 17:34
0

Why not just apply the styles to the anchor tag itself; Fiddle

.myDiv {
    text-align:center;
}
.myDiv a {
    text-decoration:none;
    background:lightblue;
    padding: 5px;
}
Novocaine
  • 4,692
  • 4
  • 44
  • 66
0

How about this:

#container
{
    text-align:center;
}
.myDiv
{
    background:lightblue;
    display:inline;
}

.myDiv a
{
     text-decoration:none;
}

And:

<body>
    <div id="container">
        <div class="myDiv">
            <a href="google.com">google.com</a>
        </div>
    </div>
</body>

Check out this JFiddle: http://jsfiddle.net/VvL6M/11/

Tom G
  • 3,650
  • 1
  • 20
  • 19