Home > Net >  Cannot align center with css
Cannot align center with css

Time:10-27

It should be a VERY simple thing to do. But somehow I managed to not accomplish!

How can I align the hex-color-picker to center horizontally?

<template>
    <div :onSelected="onSelected" :color="color" >
        <div >
            <hex-color-picker :color="color" @color-changed="handleColorChanged"></hex-color-picker>
        </div>
        <output>{{color}}</output>
    </div>
</template>

<script setup lang="ts">
import {ref} from "vue"
import 'vanilla-colorful';

const props = defineProps({
  onSelected : {
    type : Function,
  },
  color : {
    type : String,
  }
})

const color = ref(props.color)

function handleColorChanged(event) {
    color.value = event.target.color;
    console.log("handleColorChanged",event.target.color,props.onSelected)
    props.onSelected(color.value)
}
</script>

<style scoped>
    output {
        display: block;
        margin-top: 10px;
        font-size: 1.25rem;
        text-align: center;
    }
    .colorpicker {
        text-align: center;
        background-color: gray;
        width: 200px;
        align-self: center;
        align-content: center;
    }
    .colorpickerBase {
        text-align: center;
        background-color: white; 
        padding: 20px;
        margin: 20px;
    }
</style>

Tried to set every parameter to center, but still this code does not align hex-color-picker to the center.. Setting align-self etc.. doesn't even move anything.

How can I do that??

CodePudding user response:

Your .colorpicker class is using align-self and align-content properties which are only valid in Flex Layout (eg: display: flex). Similarly, the text-align property is only valid for inline elements such as images, text, or ones otherwise setting 'display: inline`.

There are many ways to center elements in CSS. It largely comes down to what layout mode is in the current context. In your case, this is a block element[1] in Flow layout[2].

Because you are setting a deterministic width on the element to bo centered, you can use auto margin:

.colorpicker {
  /* Sets 0 vertical margin, auto horizontal margin */
  margin: 0 auto;
  width: 200px;
}

This only works because CSS can determine an exact width for the element. If it cannot, then it will not work.

[1]: It's a block-element because that is the default type for div. Whereas inline is the default for something like span.

[2]: Flow layout is the default algorithm used by CSS if nothing else is specified.

  • Related